如何创建自动返回功能MOCK_METHOD?

how to create MOCK_METHOD of auto return fuction?

提问人:user3416447 提问时间:10/31/2023 更新时间:11/16/2023 访问量:28

问:

例如,有一些类

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, (), ());
};

然后,编译失败。 我该怎么办? 我无法更改原始类结构(类foo)。

C++17 谷歌测试

评论

0赞 Ted Lyngmo 10/31/2023
“但它不起作用” - 请附上您收到的确切错误消息,或准确描述它是如何不起作用的。

答:

0赞 Quarra 11/16/2023 #1

无论如何,您都无法模拟非虚拟方法。如果您无法修改,那么我看到的唯一选择是使用基于模板的依赖注入。“它不起作用”是因为您可能尝试在预期的位置注入,并且调用正在调用基类方法,因为没有发生动态调度(没有虚拟函数),因此实际上没有被调用。看:foobarfooafoo::abar::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

现场示例:https://godbolt.org/z/E3nEfTjEK