Reputation: 859
I have written a Google Test (using Google Mock). Here is the relevant code:
MockObj * obj = new MockObj ();
MockDI * mock_di = new DI();
MockDIPtr mock_di_ptr(mock_di); // boost shared ptr
Data data; // sort of on array
data.append(1); data.append(2); // Add two entries
EXPECT_CALL(*obj, get_di_ptr()).WillOnce(Return(mock_di_ptr));
EXPECT_CALL(*mock_di_ptr, get_data(_,_)).WillOnce(SetArgReferee<1>(data));
EXPECT_CALL(*obj , enqueue(_)).Times(2);
The actual implementation is:
di_ptr->get_data(int, data); // data is updated via reference
for (int i = 0; i < data.size(); ++i)
{
enqueue(data[i]);
}
Basically, enqueue()
should be called once for each entry in data. Also, the mocks are normal mocks (not Strict etc.)
This test, as expected, passes when I check for Times(2)
.
This test, as expected, fails when I check for Times(0)
or Times(1)
.
BUT, This test PASSES when I check for Times(3)
!
Why? What should I do to detect that behavior?
Upvotes: 0
Views: 704
Reputation: 118
MockDI * mock_di = new DI();
should probably read MockDI * mock_di = new MockDI();
to make the line EXPECT_CALL(*mock_di_ptr, get_data(_,_)).WillOnce(SetArgReferee<1>(data));
work.
aleguna made a good point. The following simplified experiment yields the error Actual function call count doesn't match EXPECT_CALL(mock, mockMe(_))...
. I suggest to debug the method under test and check data.size()
after di_ptr->get_data()
. Then set a breakpoint in Data::append()
and see who adds more elements.
#include "gtest\gtest.h"
#include "gmock\gmock.h"
using ::testing::_;
class Dependency
{
public:
virtual ~Dependency() {}
virtual void mockMe(int i);
};
void Dependency::mockMe(int i)
{
}
class MockDependency : public Dependency
{
public:
MOCK_METHOD1(mockMe, void (int i));
};
class Cut
{
public:
void testMe(Dependency& dependency);
};
void Cut::testMe(Dependency& dependency)
{
for (int i=0; i<2; ++i)
{
dependency.mockMe(i);
}
}
TEST(Experiment, VerifyExactCallCount)
{
MockDependency mock = MockDependency();
Cut cut;
EXPECT_CALL(mock, mockMe(_)).Times(3);
cut.testMe(mock);
}
Upvotes: 2