c++ - 为什么 Google Mocks 发现这个函数调用不明确?

标签 c++ templates compilation cppunit googlemock

我在尝试开始使用 Google Mocks 时遇到了一个问题 - 由于某种原因,它无法告诉我在 EXPECT_CALL 宏中指定的调用,即使类型是一致的.我想知道为什么它不只匹配第一个函数,以及我需要做什么/添加以使其匹配第一个函数。

模拟类:

class GMockTest : public ITest
{
public:
MOCK_METHOD2(SetParameter,
    int(int nParameter, double value));
MOCK_METHOD2(SetParameter,
    int(int nParameter, int value));
MOCK_METHOD2(SetParameter,
    int(int nParameter, __int64 value));
}

抛出错误的测试代码:

__int64 nFrom = 0,
    nTo = 0;

EXPECT_CALL(mock, SetParameter(2, nFrom))
    .Times(1)
    .WillOnce(Return(0));
EXPECT_CALL(mock, SetParameter(3, nTo))
    .Times(1)
    .WillOnce(Return(0));

编译错误:

test.cpp(1343) : error C2668: GMockTest::gmock_SetParameter' : ambiguous call to overloaded function
        testmocks.h(592): could be 'testing::internal::MockSpec<F> 
 &GMockTest::gmock_SetParameter(const testing::Matcher<T> &,const testing::Matcher<A2> &)
'
        with
        [
            F=int (int,__int64),
            T=int,
            A2=__int64
        ]
        testmocks.h(590): or       'testing::internal::MockSpec<F>  
&GMockTest::gmock_SetParameter(const testing::Matcher<T> &,const testing::Matcher<T> &)'

        with
        [
            F=int (int,int),
            T=int
        ]
        testmocks.h(580): or       'testing::internal::MockSpec<F> 
&GMockTest::gmock_SetParameter(const testing::Matcher<T> &,const testing::Matcher<FloatT
ype> &)'
        with
        [
            F=int (int,double),
            T=int,
            FloatType=double
        ]
        while trying to match the argument list '(int, __int64)'

最佳答案

Google mock 无法判断使用哪个重载。来自 cookbook ,尝试使用 Matcher<T>TypedEq<T>匹配器来指定确切的类型:

struct ITest
{
    virtual int SetParameter(int n, double v) = 0;
    virtual int SetParameter(int n, int v) = 0;
    virtual int SetParameter(int n, __int64 v) = 0;
};

struct MockTest : public ITest
{
    MOCK_METHOD2(SetParameter, int(int n, double v));
    MOCK_METHOD2(SetParameter, int(int n, int v));
    MOCK_METHOD2(SetParameter, int(int n, __int64 v));
};

TEST(Test, Test)
{
    MockTest mock;
    __int64 nFrom = 0, nTo = 0;
    EXPECT_CALL(mock, SetParameter(2, Matcher<__int64>(nFrom)));
    EXPECT_CALL(mock, SetParameter(3, Matcher<__int64>(nTo)));

    mock.SetParameter(2, nFrom);
    mock.SetParameter(3, nTo);
}

关于c++ - 为什么 Google Mocks 发现这个函数调用不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14844720/

相关文章:

c++ - 非类型模板参数的引用

c++ - 如何在单个模板调用中传递 const_iterator 和非 const 迭代器

.net - 在 VS2010 中为 .NET 4 和 Silverlight 4 交叉编译而不复制文件

c++ - Cortex A9 NEON 与 VFP 使用混淆

c++ - 如何在 Qt 中使用两个键修饰符设置 3 键序列快捷方式?

c++ - 模板的另一个问题

android - 为 android 编译 GDB 二进制文件——这可能吗?

Java泛型接口(interface)实现不能省略类型参数?

c++ - Visual Studio 中的 native C++ 程序

c++ - mysql_num_rows 总是返回 0