简体   繁体   中英

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 ?

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.

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
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM