I am trying to implement a mock method and verify that the same is only called. Below is a simple example where I am trying to mock Class A:ShowPubA2 method. Hence I have the below code:
class A {
public:
virtual void ShowPubA1()
{
std::cout << "A::PUBLIC::SHOW..1" << std::endl;
}
virtual int ShowPubA2(int x)
{
std::cout << "A::PUBLIC::SHOW..2 " << x << std::endl;
return x;
}
};
class MockA : public A {
public:
MOCK_METHOD0(ShowPubA1, void());
MOCK_METHOD1(ShowPubA2, int(int x));
};
Now I declare another class B inheriting from A -
class B : public A
{
public:
int ShowPubB2(int x)
{
ShowPubA2(x);
std::cout << "B::PUBLIC::SHOW..2 " << x << std::endl;
return x;
}
};
Below is my TEST case details:
TEST(FirstB, TestCall) {
using ::testing::_;
MockA a;
EXPECT_CALL(a, ShowPubA2(_)).Times(AtLeast(1));
B b;
EXPECT_EQ(2, b.ShowPubB2(2));
}
From the output we can see that the actual implementation is called and not the mock methods - hence the test fails:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from Firstb
[ RUN ] Firstb.TestCall
A::PUBLIC::SHOW..2 2
B::PUBLIC::SHOW..2 2
c:\myuser\documents\c and c++\gmock\consoleapplication1\consoleapplicati
n1\consoleapplication1.cpp(69): error: Actual function call count doesn't match
EXPECT_CALL(a, ShowPubA2(_))...
Expected: to be called at least once
Actual: never called - unsatisfied and active
[ FAILED ] Firstb.TestCall (0 ms)
[----------] 1 test from Firstb (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] Firstb.TestCall
1 FAILED TEST
Press any key to continue . . .
Please let me know how can I mock a method and called upon in place of its actual.
You should change B
to inject A
to something like:
class B
{
public:
explicit B(A& a) : a(&a) {}
int ShowPubB2(int x)
{
a->ShowPubA2(x);
std::cout << "B::PUBLIC::SHOW..2 " << x << std::endl;
return x;
}
private:
A* a;
};
and then
TEST(FirstB, TestCall) {
using ::testing::_;
MockA a;
EXPECT_CALL(a, ShowPubA2(_)).Times(AtLeast(1));
B b(a);
EXPECT_EQ(2, b.ShowPubB2(2));
}