Using mocks and death tests(使用模拟和死亡测试)
本文介绍了使用模拟和死亡测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现Google测试有一个意想不到的行为,当涉及到死亡测试和对模拟对象的期望时。
检查以下示例:
#include <gmock/gmock.h>
#include <cassert>
class Interface
{
public:
virtual void foo() = 0;
};
class InterfaceMock : public Interface
{
public:
MOCK_METHOD0(foo, void());
};
class Bar
{
public:
void call(Interface& interface)
{
interface.foo();
assert(false);
}
};
TEST(BarTest, call_fooGetsCalledAndDies)
{
InterfaceMock mock;
EXPECT_CALL(mock, foo());
ASSERT_DEATH({ Bar().call(mock); }, "");
}
测试失败,因为对mock.foo()
的预期调用未能断言:
Running main() from gmock_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from BarTest
[ RUN ] BarTest.call_fooGetsCalledAndDies
[WARNING] /tmp/tmp.sHHkM/gmock-1.7.0/gtest/src/gtest-death-test.cc:825:: Death tests use fork(), which is unsafe particularly in a threaded context. For this test, Google Test couldn't detect the number of threads.
foo.cc:31: Failure
Actual function call count doesn't match EXPECT_CALL(mock, foo())...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] BarTest.call_fooGetsCalledAndDies (1 ms)
[----------] 1 test from BarTest (1 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (2 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] BarTest.call_fooGetsCalledAndDies
1 FAILED TEST
有趣的是,如果EXPECT_CALL(mock, foo())
行被注释,Google Mock会发出警告,警告意外调用mock.foo()
:
Running main() from gmock_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from BarTest
[ RUN ] BarTest.call_fooGetsCalledAndDies
[WARNING] /tmp/tmp.sHHkM/gmock-1.7.0/gtest/src/gtest-death-test.cc:825:: Death tests use fork(), which is unsafe particularly in a threaded context. For this test, Google Test couldn't detect the number of threads.
GMOCK WARNING:
Uninteresting mock function call - returning directly.
Function call: foo()
Stack trace:
[ OK ] BarTest.call_fooGetsCalledAndDies (1 ms)
[----------] 1 test from BarTest (1 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[ PASSED ] 1 test.
我猜这与使用fork()
和线程的死亡测试警告有关,但我无法将所有片段匹配在一起。
推荐答案
这是known limitation死亡测试。在内部assert_death
派生,因此在子进程中调用的模拟不会在父进程中注册。如果要取消显示警告,请考虑使用NiceMock
。
这篇关于使用模拟和死亡测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用模拟和死亡测试
基础教程推荐
猜你喜欢
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01