Search code examples
c++unit-testinggoogletestros

C++ - Creating a Spy in unit tests


I have some C++ code as follows:

class MyClass
{
public:
    MyClass(OtherClass *obj)
    {
        obj_ = obj;
    }
    void myMethod()
    {
        // Do something
        int value = obj_->otherMethod();
        // Do something else
    }
private:
    OtherClass *obj_;
}

I want to create a unit test to test the functionality of myMethod(). Unfortunately, OtherClass is an external library and its methods are not declared virtual (so I can't inherit the methods and stub them out in a mock). I have some experience with Mockito where I might have used a spy for this purpose. But I can't seem to find an equivalent in C++.

I'm using the googletest framework for now and the context for this question (if it helps) is in ROS, where I'm actually trying to stub out tf::TransformListener.

Question 1: Is there an alternative to spies that I might not know of and can leverage in this situation?

Question 2: If there isn't, is there a quick-and-easy way for me to restructure my code so that I can leverage a mock?


Solution

  • Solved by doing the following:

    class IOtherMethodAdapter
    {
    public:
        virtual int otherMethod() = 0;
    }
    
    class OtherClassOtherMethodAdapter : public IOtherMethodAdapter
    {
    public:
        int otherMethod() { return obj_->otherMethod(); }
    private:
        OtherClass *obj_;
    }
    

    Now I use a pointer to IOtherMethodAdapter in MyClass instead of OtherClass and for testing I simply initialize the implementation of the interface to a stubbed/mock object. If there is another way, feel free to post that solution too.