JohnDoe
JohnDoe

Reputation: 915

Unit Test - call a function in two test cases if the function is called only once in productive code

maybe there is someone who has experience with Unit Testing with cpputest.

I have something like this:

Source code Under Test:

main_function()
{
   static int8 is_functioncalled = 1;

   if (is_functioncalled){
   my_local_function();
   is_functioncalled = 0
   }

UNIT Test Environment:

TEST(TESTGROUP,TEST_CASE1){

   //Some Unit Test checks of my_local_function()

   main_function();
}

TEST(TESTGROUP,TEST_CASE2){

   //Some other Unit Test stuff

   main_function();        // --> my_local_function() will not be called in this test case because it's called already before

}

I need in TEST_CASE2 the function my_local_function() to be called again. This function is indirectly called through the public interface main_function() which can be called directly within the Unit Test. Does anybody have an idea how to do this in generally or in cpputest environment ?

Upvotes: 2

Views: 693

Answers (2)

Viktor Juhász
Viktor Juhász

Reputation: 41

You may add a define into your code, modifying behaviour if it is under testing:

    main_function()
    {
        static int8 is_functioncalled = 1;
    #ifdef UNITTEST
        is_functioncalled = 1;
    #endif
        if (is_functioncalled){
            my_local_function();
            is_functioncalled = 0
        }

Upvotes: 1

Kamil Flaga
Kamil Flaga

Reputation: 106

Try to override setup() method of test group - it will be called before each test. You could reset is_functioncalled flag there if you would put it in global scope, something like this:

static int8 is_functioncalled = 1;
main_function()
{
   if (is_functioncalled){
   my_local_function();
   is_functioncalled = 0
   }
}

//

extern int8 is_functioncalled; // If its in global scope in other source file

TEST_GROUP(TESTGROUP)
{
   void setup()
   {
      is_functioncalled = 1;
   }
}

Try https://cpputest.github.io/manual.html - there's all you need to know.

Upvotes: 2

Related Questions