我的一个使用模拟对象和死亡测试的 googletest 单元测试有问题。这是说明问题的最小化代码示例:
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace ::testing;
class MockA {
public:
MockA() {};
virtual ~MockA() {};
MOCK_METHOD1(bla,int(int));
};
class B {
public:
B(MockA * a)
: a_(a) {};
void kill() {
exit(1);
}
MockA * a_;
};
TEST(BDeathTest,BDies) {
MockA * a = new MockA();
ON_CALL(*a,bla(_)).WillByDefault(Return(1));
B * b = new B(a);
EXPECT_DEATH(b->kill(),"");
delete a;
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
输出:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from BDeathTest
[ RUN ] BDeathTest.BDies
gtest.cc:27: ERROR: this mock object (used in test BDeathTest.BDies) should be deleted but never is. Its address is @0x7fe453c00ec0.
ERROR: 1 leaked mock object found at program exit.
[ OK ] BDeathTest.BDies (2 ms)
[----------] 1 test from BDeathTest (2 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (2 ms total)
[ PASSED ] 1 test.
似乎 googlemock 在EXPECT_DEATH
断言之后立即检查堆上剩余的模拟对象,但在调用宏之前删除a
显然不是一个好的解决方案,因为a
可能在被调用的函数中使用。我实际上希望在测试套件解构结束时进行检查。我错过了什么?