【问题标题】:OCMock - verifying order of method calls. Is there any other way?OCMock - 验证方法调用的顺序。还有其他方法吗?
【发布时间】:2013-04-24 15:50:59
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios unit-testing ocmock


    【解决方案1】:

    您可以使用setExpectationOrderMatters

    [myMock setExpectationOrderMatters:YES];
    [[myMock expect] messageA];
    [[myMock expect] messageB];
    
    [sut methodToTest];
    
    [myMock verify];
    

    【讨论】:

    • 好发现!您的答案中有小错误(messageA 然后是 messageB)。
    【解决方案2】:

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

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

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

    顺便说一句,我认为这个问题可能更适合https://codereview.stackexchange.com/,尽管我还在纠结那个网站。

    【讨论】:

      猜你喜欢
      • 2023-02-20
      • 2014-03-21
      • 2015-12-30
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多