Using google test, I would like to check that some of class methods are invoked if I call another class method.
#include "gtest/gtest.h"
class Foo {
void DoWorkPrivate(int i) {}
public:
void DoWork(int i) {}
void Run() {
for (int i = 1; i <= 5; i++) {
DoWork(i);
DoWorkPrivate(i);
}
}
};
TEST(FooTest, Run) {
Foo foo;
foo.Run(); // Need to check that DoWork() and DoWorkPrivate() are invoked
}
QUESTION:
How to check that DoWork() and DoWorkPrivate() are invoked 5 times with certain parameters (1, 2, 3, 4, 5)?
The normal way in this case is to create a Mock-Object. There are lot of literature and articles about mocking and the different types of Mocks. So I will not go to deep in detail here. e.g. fowler about mocking.
But in general you can subclass the class (or normally the interface of the class), you expect the method call.
That means for your example:
class FooMock : public Foo {
public:
bool isDoWorkPrivateCalled() {
return isDoWorkPrivatecall;
}
private:
DoWorkPrivate(int i) { isDoWorkPrivatecall = true;}
bool isDoWorkPrivatecall = false;
}
TEST(FooTest, Run) {
Foo *foo = new FooMocK();
foo->Run();
EXPECT_TRUE(foo->isDoWorkPrivateCalled());
}
And YES, that means the private methods has to be protected.
At least I suggest to use gmock. The mocking-framework extends gtest with the mock features. With gmock you could mock a method
MOCK_METHOD1(DoWorkPrivate, void(int i));
Then in your specific case, the test would look like:
EXPECT_CALL(foo, DoWorkPrivate(1)).Times(1);
EXPECT_CALL(foo, DoWorkPrivate(2)).Times(1);
EXPECT_CALL(foo, DoWorkPrivate(3)).Times(1);
EXPECT_CALL(foo, DoWorkPrivate(4)).Times(1);
EXPECT_CALL(foo, DoWorkPrivate(5)).Times(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With