使用 Google 模拟,如何在不关心/设置任何调用期望的情况下提供模拟实现

Using Google Mocks, how to give a mock implementation without caring about / setting any expectation of invocation

我有一个接口 class 说:

class MyInterface
{
public:
    virtual int doThing(int x, int y, int z) = 0;
};

我想编写一个模拟实现以用于我的测试。 E.g.Traditionally,不使用 Google 模拟,我会写说:

class MyMock : public MyInterface
{
public:
    virtual int doThing(int x, int y, int z)
    {
        if (x == 1)
            return y + z;
        else
            return y - z;
    }
};

我如何在 google 模拟中做到这一点。请注意,我不想(好吧,我不需要)对这个模拟的调用方式设置期望。我只是用它来测试其他东西。

你会怎么做(最清楚的方法是什么)?我发现 google mocks 文档有点过于简洁,无法解决这个问题。

包含 Google 模拟头文件:

#include <gmock/gmock.h>

声明一个模拟 class:

struct MyMock : MyInterface
{
    MOCK_METHOD3( doThing, int(int x, int y, int z) );
};

将模拟实例化为 NiceMock(它不会在未注册的调用时发出任何警告):

testing::NiceMock<MyMock> mock;

anything 匹配器引入范围:

using testing::_;

使用以下选项之一使用 ON_CALL 而不是 EXPECT_CALL 定义默认行为:

选项 #1

硬编码默认 return 值:

ON_CALL( mock, doThing(_,_,_) ).WillByDefault(testing::Return(0));
//                                     default return value ~~^

选项 #2

将调用委托给全局函数:

int foo(int x, int y, int z)
{
    if (x == 1)
        return y + z;
    else
        return y - z;
}

ON_CALL( mock, doThing(_,_,_) ).WillByDefault(testing::Invoke(foo));

选项#3

将调用委托给 lambda 表达式 (C++11):

ON_CALL( mock, doThing(_,_,_) ).WillByDefault(testing::Invoke(
    [] (int x, int y, int z)
    { 
        if (x == 1)
            return y + z;
        else
            return y - z;
    }
));

选项 #4

使用 Boost.Lambda 库构建 lambda 表达式:

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>

using namespace boost::lambda;

ON_CALL( mock, doThing(_,_,_) ).WillByDefault(testing::Invoke(
    ret<int>(if_then_else(_1 == 1, _2 + _3, _2 - _3))
));

// or: ret<int>(if_(_1 == 1)[_2 + _3].else_[_2 - _3])