简体   繁体   中英

How to use (GoogleMock) mock class as template paramter

I have implemented a class using policy design pattern and I need to test it using googletest/googlemock. Eg in below code, I want to test class Foo and would like to use a mock class for class Bar . Is it possible to test it using google test framework?

template <typename T>
class Foo : private T {
public:
  void foo() {
    T::bar();
  }
};

class Bar {
public:
  void bar() {
    std::cout << "Hey there!" << std::endl;
  }
};

int main() {
  Foo<Bar> f;
  f.foo();
}

You can use gmock to test templates. But, since in such scenario as yours, you do not have "direct" access to mock object, then you need to implement this access by yourself - eg with using of static member variable of Mock class - see:

class BarMock
{
public:
    // mocked method
    MOCK_METHOD0(bar, void());

    // code below is needed to keep track of created mock objects:
    BarMock() { prevIntance = lastInstance; lastInstance = this; }
    ~BarMock() { lastInstance =  prevIntance; }

    BarMock* prevIntance;
    static BarMock* lastInstance;
};
BarMock* BarMock::lastInstance = nullptr;

Then you can test in this way:

Foo<BarMock> objectUnderTest;
EXPECT_CALL(*BarMock::lastInstance, bar());
objectUnderTest.foo();

It is not possible to test it, because the template argument is a private base of the Foo template class.

If you decide to provide access to it's base class (change inheritance to public, or from a method), then it is quite simple: just create a mock class, and use as template parameter.

class BarMock
{
    MOCK_METHOD0(bar, void());
};

To test:

class TestFoo : public Test
{
public:
    TestFoo() :
        mock(),
        m( mock )
    {
    }

    Foo< BarMock > mock;
    BarMock& m;
};

TEST_F( TestFoo, test_m )
{
    EXPECT_CALL( m, bar() ).Times(1);

    mock.foo();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM