views:

60

answers:

1

At my day job I've been spoiled with Mockito's never() verification, which can confirm that a mock method is never called.

Is there some way to accomplish the same thing using Objective-C and OCMock? I've been using the code below, which works but it feels like a hack. I'm hoping there's a better way...

- (void)testSomeMethodIsNeverCalled {
    id mock = [OCMockObject mockForClass:[MyObject class]];
    [[[mock stub] andCall:@selector(fail) onObject:self] forbiddenMethod];

    // more test things here, which hopefully
    // never call [mock forbiddenMethod]...
}

- (void)fail {
    STFail(@"This method is forbidden!");
}
+1  A: 

As far as I know OCMock will fail automatically when you call verify and methods that have not been recorded were called. A mock that wouldn't complain if unexpected methods were called is called a "nice mock".

- (void)testSomeMethodIsNeverCalled {
    id mock = [OCMockObject mockForClass:[MyObject class]];

    [mock forbiddenMethod];
    [mock verify]; //should fail
}
Johannes Rudolph
That totally worked! I didn't expect it to be so simple. Just to play devil's advocate, do you think this hides the intent of the test?
Justin Voss
@Justin: Well, it requires the reader to know about OCMock's behavior in this case, which is not all too obvious. Putting a comment right next to the mock verify call should suffice to make it clear what should happen. Like: `// verify should fail because we called an unexpected method on the mock.`
Johannes Rudolph