unit-testingmockingcmocka

Should I check the input variables (pointers) in a mock function?


I am writing a series of mock functions in C using CMocka

Some of these take pointers as input variables and I am not sure whether I should check them (ptr != NULL) or not.

In general, is the mock function responsible to perform input checking?

If yes, how should it behave when an error is found? Should it use the assert functions provided by the framework?


Solution

  • If your mentioned pointers are parameters which are passed to some mocked functions you can check them with check_expected(...) and expect_value().

    void function_under_test(){
       char c = 'c'; 
       int ret;
       //...
       ret = subfunction(&c);
       if(ret == 0)
          printf("Success");
       //...
    }
    
    int __wrap_mocked_subfunction(int* p_paramater){
       check_expected(p_paramater);
       return mock();
    }
    
    test(void **state){
        expect_not_value(__wrap_mocked_functions, p_paramater, NULL);
        will_return(0);
    
        function_under_test();
    }
    

    Errors are then reported automatically.

    An example can be found here: https://lwn.net/Articles/558106/

    If you really need to check them depends on you and your code and your opinion and your requirements.