Googlemock 在测试退出时错误地报告问题。我究竟做错了什么?我已经搜索了 googlemock 文档,但是没有很好的完整示例,也没有描述我遇到的问题。
我得到的错误是:
googlemocktest.cpp(53): ERROR: this mock object should be deleted but never is.
Its address is @0018FDC4.
ERROR: 1 leaked mock object found at program exit.
一个简单测试的代码是:
#include <string>
#include <iostream>
#include <memory>
#include "gmock/gmock.h"
class IBar
{
public:
virtual ~IBar() {}
virtual void b() = 0;
virtual int c(std::string) = 0;
};
class Foo
{
private:
IBar *bar_;
public:
Foo(IBar *bar);
int a();
};
Foo::Foo(IBar *bar)
: bar_(bar)
{
}
int Foo::a()
{
// bar_->b();
return bar_->c("hello");
}
class BarMock : public IBar
{
public:
MOCK_METHOD0(b, void());
MOCK_METHOD1(c, int(std::string));
};
using ::testing::Return;
void TestAFunctionInFoo()
{
try
{
BarMock barMock;
std::unique_ptr<Foo> newFoo(new Foo(&barMock));
EXPECT_CALL(barMock, b());
EXPECT_CALL(barMock, c("hello")).WillOnce(Return(42));
newFoo->a();
}
catch (std::exception& e)
{
std::cout << "Mock exception caught: " << e.what() << std::endl;
}
catch (...)
{
}
}
int main(int argc, char* argv[])
{
::testing::GTEST_FLAG(throw_on_failure) = true;
::testing::InitGoogleMock(&argc, &argv[0]);
TestAFunctionInFoo();
return 0;
}
我已经用调试器验证了 IBar::~IBar() 确实被调用了。但我仍然收到此错误消息。如果我在 Foo::a() 中取消注释对 IBar::b() 的调用,则没有测试失败,因此不会调用 catch 语句。IBar::~IBar() 被调用,但没有错误消息表明模拟对象未被删除。
非常感谢您的帮助!