OCMock - 验证方法调用的顺序。还有其他方法吗?

时间:2013-04-24 15:50:59

标签: ios unit-testing ocmock

当我想在一个方法中验证模拟对象是按特定顺序接收某些消息时,我会这样做:

// 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];

有没有更干净/更好的方法呢? 提前谢谢。

2 个答案:

答案 0 :(得分:15)

您可以使用setExpectationOrderMatters

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

[sut methodToTest];

[myMock verify];

答案 1 :(得分:2)

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

__block BOOL hasCalledA;

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

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

你的解决方案看起来很好。

作为旁注,我认为这个问题可能更适合https://codereview.stackexchange.com/,尽管我仍然围绕着那个网站。