[英]How to check a function is called in a destructor in a unit test in C++?
In the following example, I would like to check if fooFunction
is called upon destruction of the object. 在下面的示例中,我想检查对象销毁后是否调用了
fooFunction
。
#include <gtest/gtest.h>
#include <gmock/gmock.h>
class FooClass
{
public:
~FooClass(){ FooClass::fooFunction(); }
virtual void fooFunction() {}
};
class MockFooClass : public FooClass
{
public:
MOCK_METHOD0(fooFunction, void());
};
TEST(DumbTest, blabla)
{
auto mock = new MockFooClass;
EXPECT_CALL(*mock, fooFunction());
delete mock;
}
However this test fails because the destructor of FooClass
calls FooClass::fooFunction()
instead of MockFooClass::fooFunction()
. 但是,此测试失败,因为
FooClass
的析构函数调用FooClass::fooFunction()
而不是MockFooClass::fooFunction()
。 Does anyone know of a way to do that? 有人知道这样做的方法吗?
I'm using Visual Studio 2010. 我正在使用Visual Studio 2010。
I understand why this test fails: as soon as we enter the destructor of FooClass
, the object is not a MockFooClass
any more. 我知道测试失败的原因:一旦我们输入
FooClass
的析构函数,该对象就不再是MockFooClass
。 What I'm looking for is if anyone knows of a way to get around it. 我正在寻找的是是否有人知道解决该问题的方法。
You can use Isolator++ to use check that the method was called. 您可以使用Isolator ++来检查是否已调用该方法。
class FooClass
{
public:
~FooClass(){ FooClass::fooFunction(); }
virtual void fooFunction() {}
};
TEST(DumbTest, blabla)
{
auto real = new FooClass;
auto mock = FAKE_ALL<FooClass>(FakeOptions::CallOriginal);
delete real;
ASSERT_WAS_CALLED(mock->fooFunction());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.