aaroh
aaroh

Reputation: 312

Manipulating return value of inner function for unit testing?

I am currently trying to write the unit test for some legacy code. In one of my function, it calls another function. According to the return value of the inner function, three branching conditions are present. The code is written in C++ and I am using cxxtest framework. How can I manipulate the return value of the inside function without going into the implementation of it so that I can pass through all the branching condition? I prefer to avoid dependencies between the functions. Is there any way to do this?

Upvotes: 2

Views: 596

Answers (2)

aaroh
aaroh

Reputation: 312

I found a solution. I have created a new header file called new_header.hpp. Added a function with the same syntax like socket function into the file like this :

int socket(int domain, int type, int protocol)
{
     if(domain == CONST1)
          return -1;
     else if(domain == CONST2)
          return 1;
}

Then in the cmake file, I have created a library to run UT. I added this new new_header.hpp with other required files as a dependency. Also, I have included this file in the header of my newly created UT file. Voila, by manipulating one of the values in the parameter I was able to mock the required functions. Adding the mocks for user-defined functions also work in same way.

Upvotes: 1

Jon Chesterfield
Jon Chesterfield

Reputation: 2341

There is already a dependency between the functions. One calls the other.

The solution is to change the outer function to take, as a parameter, the inner function. Then you can pass in a function which returns whatever value you like when testing and the useful function in the rest of the application.

Probably bind it at compile time, e.g.

struct inner_function {int operator()();}
struct mock {int operator ()();}

template <typename F = inner_function>
int outer_function()
{
    if (F {}())
      return 1;
    else
      return 2;
}


// in a test
int r = outer_function <mock>();

You can do this at runtime with function pointers if you prefer. I would probably add another wrapper to hide the template from client code too.

Upvotes: 2

Related Questions