当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Changing gmock expectation

问题描述:

I have a unit test I want to write in GMock. However, my familiarity is primarily with Mockito. What I would write in Mockito is:

Mockito.verify(mock, Mockito.never()).someFunctionCall(Matchers.<String>any());

doSomething(mock);

Mockito.verify(mock, Mockito.times(1)).someFunctionCall(Matchers.<String>any());

doSomethingElse(mock);

Which corresponds to verifying that doSomething never invokes someFunctionCall but is called exactly once by doSomethingElse.

How would I accomplish the same thing with GMock?

EXPECT_CALL(mock, someFunctionCall(_)).Times(0);

doSomething(mock);

EXPECT_CALL(mock, someFunctionCall(_)).Times(1);

doSomethingElse(mock);

Obviously doesn't work since the expectations stack.

网友答案:

For something like that, you'd probably want to set up two distinct tests. One for doSomething, and one for doSomethingElse. Alternately, if the behavior of the second depends on the first, you could do something like:

{
  MyMock mock;
  EXPECT_CALL(mock, someFunctionCall(_)).Times(0);
  doSomething(mock);
}
{
  MyMock mock;
  EXPECT_CALL(mock, someFunctionCall(_)).Times(1);
  doSomethingElse(mock);
}

The verification of the assertions is done on object destruction, so scoping each mock to just the set of calls that it's needed for will validate the assertions. But really, I'd probably try to separate the testing of the two methods into separate tests. If you have boilerplate setup that you don't want to repeat, stick it in the base class that your TEST_Fs derive from.

网友答案:

Mock::VerifyAndClearExpectations / Mock::VerifyAndClear can be used for these purposes.

分享给朋友:
您可能感兴趣的文章:
随机阅读: