In the following straight-forward test, GTest complains that mock is never deleted. I don't understand this behavior. If I remove the EXPECT_CALL
, it works fine.
TEST_F(TestFixture, TestName)
{
auto mock_client = std::make_unique<MockClient>();
auto mock_evaluator = std::make_unique<MockEvaluator>();
// problematic expect call
EXPECT_CALL(*mock_client, DoSomething(testing::_)).Times(1);
Runner runner(std::move(mock_client), std::move(mock_evaluator));
}
I get the following error:
xyz_test.cpp:48: ERROR: this mock object (used in test TestFixture.TestName) should be deleted but never is. Its address is @0x865510.
ERROR: 1 leaked mock object found at program exit. Expectations on a mock object is verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
Can someone please help me understand this behavior?
By using a unique_ptr
, the owner of the mock object becomes the runner
object. GTest's leak detection expects mock_client
and mock_evaluator
to be destructed within your TEST, not possibly after that.
GMock will verify the expectations on a mock object when it is destructed. See this reference .
You can either avoid using a unique pointer and construct the mock object in your test and just pass its address to your runner
object, or add this at the end of your test:
EXPECT_TRUE(Mock::VerifyAndClearExpectations(mock_client.get()));
EXPECT_TRUE(Mock::VerifyAndClearExpectations(mock_evaluator.get()));
This verifies and removes the expectations on your mock objects and returns true if and only if successful.
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.