randomThought
randomThought

Reputation: 6393

Mocking non-class methods in c++

I am trying to refactor code in a legacy application and ran into a situation where the code looks something like this

namespace DB
{
    void GetDataBase(IDataBase** db);
}

There are a lot of different places that this gets called from, and I want to test those methods but replace the result returned. Is there a certain design I can use to get this mocked correctly?

what I have is this but it doesn't seem like a good way to go, though it works

namespace DB
{
    void GetDataBase(IDataBase** db);
    void SetTestDataBase(IDataBase* db);
}

There are a lot of other similar situations and I would love to get some thoughts on how this can be improved.

Upvotes: 1

Views: 417

Answers (1)

user1708860
user1708860

Reputation: 1753

The way you suggested is OK, but it pollutes the testing code and you will probably need more then one method like this. Also note that it might not work if there are static variables that are initiated and use this function.

What i suggest doing is either one of the two -

  1. Clean the code, this is not a complicated function with lots of dependencies, you can easily change it into a simple factory call. To avoid going over all the functions that use it, you can create a macro that does it for you. The factory can then use an #ifndef statement to determine weather to take your mock or the real code. (compile the testing code with the define statement and the production code without it)
  2. You can replace the implementation at linkage time. When compiling the production code, link it with the real implementation; but when you compile the test, link it with your mock to return an object of your liking.

Both ways make sure that no static methods that are called before the main are using the get method you want to mock.

Upvotes: 1

Related Questions