jeudi 24 novembre 2016

how to write c unit tests for a basic calculator

Im trying to know how we can do some basic tests in c programs. For example I have a basic command line calculator program and I want to verify if there are bugs.

And I will need to run the same tests several times always with the same input and output and I will do some little changes in each iteration.

So instead of always be inserting the same values and check if the result is the expected, I created a little program to automate this process. The program reads each line of a text file to insert in the calculator program the inputs and compare the expected output with the output obtained.

For example the text file is like this:

10 - 5 = 5 (test case: subtraction of positive integers)
10 - 0  = 10 (test case: subtraction with zero)
10 - (-5) = (test case: subtraction with negative integers)
 ...

So in this file have the test cases where I have the inputs and outputs (the expected result) to test the subtraction operation.

But I would like to know if there arent any frameworks that are really used and more precise to do this kind of test. I was reading that unity can do this but I already tried to use but Im getting always issues that Im can not solve.

So I would like to know if you know how to this in unity or in other system and if can provide a basic exampel so I can understand?

For example I was trying to test the first test case, the subtraction of positive integers:

This is a function that I was trying to do to check the expected result with the actual result:

void test_case_subtraction_of_positive_integers(int x, int y){
    UNITY_BEGIN();
    int expected = 5;
    int actual = x-y;
    TEST_ASSERT_EQUAL(expected, actual);
    return UNITY_END();
}

This is a function of the calculator program responsible for the subtraction:

void subtraction()
{
    int a, b, c = 0;
    printf("\nPlease enter first number  : ");
    scanf("%d", &a);
    printf("Please enter second number : ");
    scanf("%d", &b);
    c = a - b;
    runTestSubtraction(10, 5);
    RUN_TEST();
    printf("\n%d - %d = %d\n", a, b, c);

}

Aucun commentaire:

Enregistrer un commentaire