Welcome to the new Parasoft forums! We hope you will enjoy the site and try out some of the new features, like sharing an idea you may have for one of our products or following a category.

How do you stub a function to return a different value each time it's called in a single test

NatePuhlman
NatePuhlman Posts: 2

I've got a function with the following code:

if (ext_test() == true) {
    ext_mod();
    if (ext_test() == true) {
        ext_in();
    }
    ext_out();
}

and I need to make a test that executes out_func() BUT NOT in_func() (the ext_test(), ext_mod(), ext_in() and ext_out() functions access data outside the function; I didn't design this BTW, I'm just testing it). We need to stub the ext_test() function to be true the first time, but false the second time it's called. However, as far as I can tell, stubbing a function will apply to every call of said function. I was able to come up with the following code in a function that is linked to the stub:

static int count = 0;
*__return = count++ % 2 == 0;

This code will return true the first time it is called, but false the second time. However, I'm hesitant to add state to a unit test, as this may cause problems later down the line.

So my question is: is there a way to accomplish this that is built into Parasoft? I feel like this kind of issue is not so rare to have no better answer.

Best Answer

  • NatePuhlman
    NatePuhlman Posts: 2
    Answer ✓

    I've found an answer, It's buried in the Parasoft manual (not online, for some reason). We can change my code from this:

    static int count = 0;
    *__return = count++ % 2 == 0;
    

    to this:

    // `stubCallInfo->callNo` starts at 1
    *__return = stubCallInfo->callNo % 2 == 1;
    

    It seems that stubCallInfo->callNo is the variable I was searching for.