例如,有一些课程
class foo
{
public:
auto a() -> bool { return true; }
};
所以我创建了这样的模拟类:
class bar : public foo
{
public:
MOCK_METHOD(bool, a, (), ());
};
但它不起作用。 所以我换了模拟课
class bar : public foo
{
public:
MOCK_METHOD(auto, a, (), ());
};
然后,编译失败。 我能怎么做? 我无法更改原始类结构(class foo)。
无论如何你都不能模拟非虚拟方法。如果你无法修改
foo
,那么我看到的唯一选择就是使用基于模板的依赖注入。 “它不起作用”是因为您可能尝试在预期 bar
的位置注入 foo
并且对 a
的调用正在调用基类 foo::a
方法,因为没有发生动态调度(没有虚拟)函数)所以 bar::a
实际上没有被调用。参见:
#include "gmock/gmock.h"
class foo {
public:
auto a() -> bool
{
return true;
}
};
class bar : public foo {
public:
MOCK_METHOD(bool, a, ());
};
TEST(BarTest, call_a) {
bar b{};
EXPECT_CALL(b, a).WillOnce(testing::Return(true));
ASSERT_TRUE(b.a());
}
bool ref_to_f(foo& f) {
return f.a();
}
TEST(BarTest, call_a_by_ref_to_f) {
bar b{};
EXPECT_CALL(b, a).WillOnce(testing::Return(true));
ASSERT_TRUE(ref_to_f(b));
}
template<class F>
bool ref_to_f(F& f) {
return f.a();
}
TEST(BarTest, call_a_by_ref_to_f_template_injection) {
bar b{};
EXPECT_CALL(b, a).WillOnce(testing::Return(true));
// note: use `ref_to_f<bar>` in tests, use `ref_to_f<foo>` in the production code
ASSERT_TRUE(ref_to_f<bar>(b));
}
给予:
[==========] Running 3 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 3 tests from BarTest
[ RUN ] BarTest.call_a
[ OK ] BarTest.call_a (0 ms)
[ RUN ] BarTest.call_a_by_ref_to_f
/app/example.cpp:31: Failure
Actual function call count doesn't match EXPECT_CALL(b, a)...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] BarTest.call_a_by_ref_to_f (0 ms)
[ RUN ] BarTest.call_a_by_ref_to_f_template_injection
[ OK ] BarTest.call_a_by_ref_to_f_template_injection (0 ms)
[----------] 3 tests from BarTest (0 ms total)
[----------] Global test environment tear-down
[==========] 3 tests from 1 test suite ran. (0 ms total)
[ PASSED ] 2 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] BarTest.call_a_by_ref_to_f