7

当我想验证在一种方法中模拟对象是否以特定顺序接收一些消息时,我会执行以下操作:

// sut is an instance of the class I am testing and myMock is a mock object injected in sut.
// I want to test that myMock sends messageA and then messageB, in that particular order.
[[[myMock expect] andDo:^(NSInvocation *invocation)
  {
      [[myMock expect] messageB];
  }]
 messageA];

 [sut methodToTest];

 [myMock verify];

有没有更清洁/更好的方法来做到这一点?提前致谢。

4

2 回答 2

15

您可以使用setExpectationOrderMatters

[myMock setExpectationOrderMatters:YES];
[[myMock expect] messageA];
[[myMock expect] messageB];

[sut methodToTest];

[myMock verify];
于 2013-04-26T20:13:20.200 回答
2

这对我来说看起来很干净。如果你不喜欢嵌套,你可以引入一个块变量。

__block BOOL hasCalledA;

[[[myMock expect] andDo:^(NSInvocation *invocation) {
    hasCalledA = YES;
  }] messageA];

[[[myMock expect] andDo:^(NSInvocation *invocation) {
    STAssertTrue(hasCalledA);
  }] messageB];

你的解决方案看起来不错。

附带说明一下,我认为这个问题可能更适合https://codereview.stackexchange.com/ ,尽管我仍在关注该网站。

于 2013-04-24T18:58:06.520 回答