【问题标题】:Mocking overloaded methods with the same number of input arguments using GMock使用 GMock 模拟具有相同数量输入参数的重载方法
【发布时间】:2021-06-17 15:00:06
【问题描述】:

我有一个类定义了我需要模拟的重载方法。问题是,这两个重载都只接受一个参数,而 GMock 似乎认为这个调用是模棱两可的。

这是一个演示问题的小例子(为了演示而过度简化):

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <iostream>
#include <string>

using ::testing::_;

class MyClass
{
public:
    virtual ~MyClass() = default;

    virtual void PrintValue(const std::string& value) const
    {
        std::cout << value << std::endl;
    }

    virtual void PrintValue(const int& value) const
    {
        std::cout << value << std::endl;
    }
};

class MyClassMock : public MyClass
{
public:
    MOCK_CONST_METHOD1(PrintValue, void(const std::string&));
    MOCK_CONST_METHOD1(PrintValue, void(const int&));
};

TEST(MyTest, MyTest)
{
    MyClassMock mock;
    EXPECT_CALL(mock, PrintValue(_)).Times(1);
    mock.PrintValue(42);
}

int main(int argc, char* argv[])
{
    ::testing::InitGoogleMock(&argc, argv);
    return RUN_ALL_TESTS();
}

EXPECT_CALL 行我得到一个编译错误:

error: call of overloaded 'gmock_PrintValue(const testing::internal::AnythingMatcher&)' is ambiguous
     EXPECT_CALL(mock, PrintValue(_)).Times(1);

如何让 GMock 正确区分这两个重载,从而使调用不再模棱两可?

【问题讨论】:

标签: c++ overloading googletest googlemock ambiguous


【解决方案1】:

我遇到了同样的问题并使用gMock Cookbook's Select Overload section 解决了它。您必须定义匹配器的类型,例如通过写Matcher&lt;std::string&gt;()。请记住在上面包含此指令 (using ::testing::Matcher;)。

【讨论】:

    猜你喜欢
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多