Un-mock Partial Mock

Discussion of the OCMock framework. If you have patches we would prefer you to send them to the mailing list, but attaching them to a topic is possible, too.

Un-mock Partial Mock

Postby antb » 14 Feb 2011, 20:28

Hi all,

With OCMock, I'm trying to set an expectation on the [NSNotificationCenter defaultCenter] object. Pretty much I want to know that the "addObserver" and "removeObserver" methods are called, without actually calling the real implementations.

For that I'd create a partial mock of the default center and then set an expectation.

However, when my test method is done, I want to ensure that the default center is no longer mocked since I'd like to use its regular implementation in other test methods.

Is there a clean way of achieving this behavior?



Re: Un-mock Partial Mock

Postby erik » 15 Feb 2011, 15:15

There are three different answers.

From a purist perspective, code should be designed so that its dependencies can be mocked explicitly, that is dependencies should be passed to the object from the outside. This pattern is known as "dependency injection" and it allows tests to use a normal mock, rather than a partial mock on a shared instance.

In this case the code that posts the notification should not post it to the default centre. Instead the class should have an instance variable with a reference to a notification centre, which in the running app would be the default centre, but in the test could be set to a regular mock.

Then, a partial mock does clean up after itself when it gets deallocated. However, with mock objects placed in an autorelease pool by default or deallocated by the garbage collector this is hard to rely on.

So, I've just added a new method on partial mocks, named stop, which when called effectively disables the partial mock. If dependency injection isn't for you, you might want to grab the latest version of OCMock from Subversion and add a [myNotificationCenterMock stop] at the end of the test that creates the partial mock for the notification centre.
Posts: 90
Joined: 10 Oct 2009, 15:22
Location: Hamburg, Germany

Return to OCMock