在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();
}
}
答案 0 :(得分:1)
很少有方法可以为您服务。我喜欢将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
的函数可以是与您要覆盖的方法签名匹配的任何函数。在这种情况下,它是一个函数,该函数计算模拟已被调用的次数并返回适当的值。您还可以为msg
输出参数分配一些特定的对象。