在代码Google Mock测试代码段中,有一个EXPECT_CALL
,它返回True并且参数引用为200次。
我怎样才能让测试每第n次返回True。例如,每次第10次调用返回True,否则返回False。
class MockHandler : public Handler
{
public:
MOCK_METHOD1(RxMsg, bool(Msg &msg));
}
TEST(TestDispatcher, HandlePing)
{
auto mockedHandler = make_unique<MockHandler>();
Msg rxMsg = { REQUEST::REQ_PING, sizeof(DefaultMsg_t), rxMsg.rx,(uint8_t*)"0"};
EXPECT_CALL(*mockedHandler,
RxMsg(_)).Times(checkValue).WillRepeatedly(
DoAll(SetArgReferee<0>(rxMsg), Return(TRUE)));
Dispatcher dispatcher(10, mockedHandler);
for (int i = 0; i < 199; i++)
{
dispatcher.RunToCompletion();
}
}
很少有方法可能对您有用。我喜欢用Invoke
作为默认动作的解决方案,因为它是最灵活的。你没有在你的问题中提供mcve,所以我为你使用的类编写了非常简单的实现。你使用unique_ptr
进行模拟也犯了一个错误。在99%的情况下必须是shared_ptr
,因为您在测试环境和被测系统之间共享它。
class Msg {};
class Handler {
public:
virtual bool RxMsg(Msg &msg) = 0;
};
class MockHandler: public Handler
{
public:
MOCK_METHOD1(RxMsg, bool(Msg &msg));
};
class Dispatcher {
public:
Dispatcher(std::shared_ptr<Handler> handler): h_(handler) {}
void run() {
Msg m;
std::cout << h_->RxMsg(m) << std::endl;
}
private:
std::shared_ptr<Handler> h_;
};
class MyFixture: public ::testing::Test {
protected:
MyFixture(): mockCallCounter_(0) {
mockHandler_.reset(new MockHandler);
sut_.reset(new Dispatcher(mockHandler_));
}
void configureMock(int period) {
ON_CALL(*mockHandler_, RxMsg(_)).WillByDefault(Invoke(
[this, period](Msg &msg) {
// you can also set the output arg here
// msg = something;
if ((mockCallCounter_++ % period) == 0) {
return true;
}
return false;
}));
}
int mockCallCounter_;
std::shared_ptr<MockHandler> mockHandler_;
std::unique_ptr<Dispatcher> sut_;
};
TEST_F(MyFixture, HandlePing) {
configureMock(10);
for (int i = 0; i < 199; i++) {
sut_->run();
}
}
在每个测试开始时,您应该调用configureMock
方法,该方法将调用ON_CALL
宏设置模拟的默认操作。传递给Invoke
的函数可以是与您要覆盖的方法的签名匹配的任何函数。在这种情况下,它是一个函数,它计算已经调用了mock的次数并返回适当的值。您还可以将一些特定对象分配给msg
输出参数。