Search code examples
c++unit-testingfunctionmockingstatic-functions

Best simple way to mock static/global function?


I have a simple almost value-like class like Person:

class Person
{
public:
    Person(ThirdPartyClass *object);
    virtual ~Person(void);

    virtual std::string GetFullName() const;
    virtual int GetAge() const;
    virtual int GetNumberOfDaysTillBirthday() const;
};

I'm using a third party library and the ThirdPartyClass needs to have a global/static function called Destroy (part of the 3rd party library) called on it to destroy it. This Destroy function is called in the Person destructor.

Now I'm trying to unit test my Person class and I need a way to mock/stub the Destroy method. I think I could write a wrapper class around the static Destroy function and then use dependency injection to inject this wrapper into the Person class, but it seems like overkill to do that just to call this one function on this simple class. What's a simple straightforward way to do this? Or is dependency injection really the best way to do this?

Update

Ultimately I decided to go with creating a class that wrapped all the 3rd party library's global functions and then using dependency injection to pass this class into the constructor of my person class. This way I could stub out the Destroy method. Although the person class only uses a single function, the other functions of the library are called at other points in my code and as I needed to test those I would face the same issue.

I create a single instance of this wrapper class in my main app code and inject it where needed. I chose to go this route because I think it's clearer. I like Billy ONeal's solution and I think it answers my question, but I realized if I were to leave the code for a few months and come back it would take me longer to figure out what was happening as compared to dependency injection. I'm reminded of the zen of python aphorism "Explicit is better than implicit." and I feel dependency injection makes what's happening a bit more explicit.


Solution

  • Create a link seam. Put your destroy declaration in a header, and then have two implementation files:

    // Destroy.cpp
    void Destroy()
    {
        //Code that really does destruction
    }
    

    And for testing:

    // DestroyFake.cpp
    void Destroy()
    {
        //Code that does fake destruction
    }
    

    Then link the first file to your main binary, and the second file to your testing binary.

    Beyond this, what you ask for is impossible. The linker bakes calls to global functions and static methods into direct jumps into the callee code -- there's no lookup or decision process to hook into to create any type of overload like the one you're looking for (beyond having Destroy calling something that's more easily mocked).