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.
ThirdPartyClass
instead as a stub. – GatepostThirdPartyClass
using googlemock, butThirdPartyClass
needs to haveDestroy
called on it to clean up. – JustinPerson
doesn't callDestroy
. I though you asked how to implement it, how to call it is entirely different issue. – Gatepost