为什么Google Mocks发现此函数调用不明确?

dla*_*nod 16 c++ templates cppunit compilation 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));
}
Run Code Online (Sandbox Code Playgroud)

抛出错误的测试代码:

__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));
Run Code Online (Sandbox Code Playgroud)

编译错误:

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)'
Run Code Online (Sandbox Code Playgroud)

con*_*gus 28

Google模拟无法确定要使用哪种重载.从食谱中,尝试使用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);
}
Run Code Online (Sandbox Code Playgroud)


小智 9

对于那些有同样问题但不像 OP 没有或不关心输入参数的人,使用 testing::Matcher 的另一个答案的解决方案可以与通配符 testing::_ 结合使用:

EXPECT_CALL(mock, SetParameter(testing::_, Matcher<__int64>(testing::_)));
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下使用以下内容会更容易阅读并且更有意义。`testing::A&lt;__int64&gt;() 或 testing::An&lt;__int64&gt;()` (3认同)