samedi 30 juillet 2016

Function mocking in C?

I'm writing a unit-test to check some API calls. I am using check to test. My module is build with CMake (idk if it matters).

My test calls a function (which I need to test) and this function makes a call to another binary.

Simplified version of it looks like this.

/* unitTest.c */

#include "libraryAPI.h"
void letsMakeACall(void)
{
   ck_assert_eq(foo("water"), 0);
}

-- Module I am working on---
/*libraryAPI.c*/
#include "legacyLib.h"

void foo(const char *drink )    
{

    if (checkDrink(drink)!=0)
    {
       return 1;
    }else
    {
       return 0;
}


----LEGACY BINARY---
/*legacyLib.c*/

static const char* expected = "water";

void checkDrink(const char *drink)
{
    if(drink == expected)
     {
        /*There are also a dozen functions being called which depend on legacy module initialisation*/
        return 0;
     }else{
        return 1;
     }
}

I'd like to mock response from legacyLib, because otherwise it call dozens of functions and breaks. My initial idea was to add some ifdef conditions when tests are being run, but it is against guidelines. Because it is basically a call interception I don't know what it a best(or working) solution. What can I use to solve it?

Aucun commentaire:

Enregistrer un commentaire