nap*_*con 4 c++ unit-testing googlemock
我有一个接口类说:
class MyInterface
{
public:
virtual int doThing(int x, int y, int z) = 0;
};
Run Code Online (Sandbox Code Playgroud)
我想编写一个模拟实现,以便在我的测试中使用.例如,传统上,不使用谷歌模拟,我会写:
class MyMock : public MyInterface
{
public:
virtual int doThing(int x, int y, int z)
{
if (x == 1)
return y + z;
else
return y - z;
}
};
Run Code Online (Sandbox Code Playgroud)
我将如何在谷歌模拟中这样做.请注意,我不想(好的,我不需要)设置关于如何调用这个模拟的期望.我只是用它来测试别的东西.
你会怎么做(以及最清晰的方式)?我发现google mocks文档有点过于简洁,无法解决这个问题.
Pio*_*cki 16
包含Google Mock头文件:
#include <gmock/gmock.h>
Run Code Online (Sandbox Code Playgroud)
声明一个模拟类:
struct MyMock : MyInterface
{
MOCK_METHOD3( doThing, int(int x, int y, int z) );
};
Run Code Online (Sandbox Code Playgroud)
将模拟实例化为NiceMock(在未注册的调用时不会发出任何警告):
testing::NiceMock<MyMock> mock;
Run Code Online (Sandbox Code Playgroud)
将任何匹配器带到范围:
using testing::_;
Run Code Online (Sandbox Code Playgroud)
与定义默认行为ON_CALL,而不是EXPECT_CALL使用下面的选项之一:
硬编码默认返回值:
ON_CALL( mock, doThing(_,_,_) ).WillByDefault(testing::Return(0));
// default return value ~~^
Run Code Online (Sandbox Code Playgroud)
将调用委托给全局函数:
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));
Run Code Online (Sandbox Code Playgroud)
将调用委托给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;
}
));
Run Code Online (Sandbox Code Playgroud)
使用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])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7958 次 |
| 最近记录: |