【发布时间】:2011-12-08 05:20:10
【问题描述】:
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() 被调用,但没有错误消息表明模拟对象未被删除。
非常非常感谢您的帮助!
【问题讨论】:
-
Bleh,恐怕没有答案,但是用 gcc 4.6.1 在 Fedora 15 上使用 gtest/gmock 1.5 确认了您的行为。你试过 gmock 列表/组吗?
-
只是想为后代指出,虽然这不是您的问题,但当您忘记模拟界面上的虚拟析构函数时会出现相同的错误 - 这非常微妙,可能会让您盯着在代码上花了很长时间......
标签: c++ testing googlemock