Search code examples
iosocmockito

Verify method call within init* with OCMockito


I would like to test if my init* method calls some other method within its body with OCMockito. Is this possible and if, how can I do it? Let's say, that I want to check if [self myMethod] has been called.

I've been trying to do it in a such naive way, but as you can imagine, with no success:

it(@"should trigger myMethod", ^{
    DetailsView *mockDetailsView = mock([DetailsView class]);
    [mockDetailsView initWithFrame:CGRectZero];
    [verify(mockDetailsView) myMethod];
});

Solution

  • There are three possibilities depending of myMethod functionality.

    Move myMethod call out from init

    If myMethod realises very concrete logic of the object it should probably be called explicitly by the object's owner. Object creation shouldn't do anything more than setting its initial state. Then, if it's not in init it's easy to test.

    Check object's state

    If 'myMethod` configures object in some way, you can test its properties or its state rather than check if the method was called, because it's secondary - the final result is important.

    Test the method...

    Finally, if you really need to test whether myMethod was called, and none of above applies (which shouldn't happen), you can set in the method body a property self.myMethodCalled = YES. This is super ugly, so you can derive from your class, override myMethod and set the property there, and then verify this call testing the subclass (which is unsafe and impure).

    This is really hacky and indicates that probably something's wrong from the object design perspective.