nland
nland

Reputation: 669

Verify a method was called from another object OCMock

I have two classes.

Object 1:

- (void) methodA {
    ObjectB objectB = [[ObjectB alloc] init];
    [objectB methodB];
}

And Object 2:

- (void) methodB {
     // Does something
}

Using OCMock, how do I verify that methodA calls methodB? I'm setting the test up like the following:

id mock = OCMClassMock([Object2 class]);
OCMStub([mock methodB).andReturn(nil);

[self.object1 methodA];
OCMVerify([mock methodB]);

The test class is testing object1, but I'd like to verify that it calls the method on object2. When running this test, I get the failing message:

Method methodB was not invoked.

I'm still really new to mocks/stubs. It's entirely possible that I'm structuring the test wrong. The mock confuses me a little because I'm testing Object1, but trying to verify something on Object2.

Am I thinking correctly when I am setting up this test? If not, how should I approach this?

Upvotes: 2

Views: 1049

Answers (1)

Erik Doernenburg
Erik Doernenburg

Reputation: 3014

You have to make sure (somehow) that Object1 uses the mock and not a fresh instance of ObjectB. The usual approach to do this is dependency injection, ie. Object1 has a dependency on Object2, but instead of Object1 creating an instance of Object2, the instance of Object2 is set from the outside (injected). There's a huge amount of stuff about it on the web.

With OCMock you could hack your way around this another way. This is not recommended, though. You could replace alloc/init with new, then stub the new class method to return the mock. That way Object1 would use the mock without even knowing it. It would still "think" that it allocated a fresh instance of Object2.

id mock = OCMClassMock([Object2 class]);
OCMStub([mock new]).andReturn(mock);
OCMStub([mock methodB).andReturn(nil);

[self.object1 methodA];
OCMVerify([mock methodB]);

This is mentioned in the reference documentation in 9.3. Stubbing methods that create objects.

Upvotes: 1

Related Questions