OCMock - verifying order of method calls. Is there any other way?
Asked Answered
E

2

7

When I want to verify that in one method a mock object is receiving some messages in a particular order I do something like this:

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

Is there any cleaner/better way of doing this? Thanks in advance.

Emission answered 24/4, 2013 at 15:50 Comment(0)
B
15

You can use setExpectationOrderMatters

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

[sut methodToTest];

[myMock verify];
Bargeman answered 26/4, 2013 at 20:13 Comment(1)
Good find! Minor typo in your answer (messageA then messageB).Outandout
O
2

That looks pretty clean to me. If you're not happy nesting, you could introduce a block variable.

__block BOOL hasCalledA;

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

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

You solution looks fine though.

As a side note, I think this question might be better suited for https://codereview.stackexchange.com/ although I'm still wrapping my head around that site.

Outandout answered 24/4, 2013 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.