How to test inside a for loop (unit testing)

1.7k views Asked by At

I'm using VectorCAST for unit testing, with Green Hills compiler and Renesas v850e2v3 microcontroller, and VectorCAST indicates that I have two branches to test in the following for loop.

typedef enum
{
    MIN_ENUM_VAL = 0x00,
    ENUM_VAL_1   = 0x01,
    ENUM_VAL_2   = 0x02,
    MAX_ENUM_VAL
} Enumeration_T;

void myFunction (void)
{
    int counter;
    for(counter = MIN_ENUM_VAL; counter < MAX_ENUM_VAL; counter++)
    {
        //Do something.
    }

    //Do something else.
}

How can I test these branches? Really I don't have idea on how to test inside the for loop.

3

There are 3 answers

0
Gugyin Adrián On

If you insert a test case under myFunction() and run it, it should automatically pass through both branches, as the enum values less than MAX_ENUM_VAL satisfy the 'true' branch and MAX_ENUM_VAL satisfies the 'false' branch. VectorCAST understands branches in for loops as conditional branches with respect to the middle sub-statement. It can be seen by inserting the basis path test cases, then reading the notes section of the generated test cases.

0
SKY On

Depending upon the code coverage and options you select, you can enable or disable branch conditions for the loop control variables. The idea behind measuring loop code coverage is to ensure statements inside the loop execute until the end i.e. no. of iterations to ensure expressions are evaluated as per the design. It may happen after halfway through the loop there some exception being generated and control will exit from the for loop before completion of specified loop iterations.

Looking at the example of your for loop, if loop executes for counter=MIN_ENUM_VAL to counter=MAX_ENUM_VAL, then the tool will show you've covered both True and False branch of condition counter < MAX_ENUM_VAL unless the loop body has some condition which calls a break before counter=MAX_ENUM_VAL.

1
John Burger On

Your definition looks suspicious:

typedef enum
{
    MIN_ENUM_VAL = 0x00,
    ENUM_VAL_1   = 0x01,
    ENUM_VAL_2   = 0x02,
    MAX_ENUM_VAL
} Enumeration_T;

Do you really mean that the first enum value is 1? What about 0? Is that a legal value? Is MIN_ENUM_VAL really 0? Or 1? I'd've expected:

MIN_ENUM_VAL = 0x00,
ENUM_VAL_1   = MIN_EUM_VAL,

MAX_ENUM_VAL is a more regular definition. Incorrect, but regular. The correct "maximum" is 2 - the 'normal' definition for what you have is LAST_ENUM_VAL, which is one more than the true "maximum" or "last" one (hypocritical, I know. But who defines these conventions anyway?).