Tag Archives: OCMock

NSNotificationCenter part 3: Unit testing notifications with OCMock

This article is the third part of a series about NSNotificationCenter. Head over part 1 for the basics of receiving and sending notifications.

In order to avoid writing unit tests we are sometimes eager to declare our code as “untestable”. Like most code, notifications can be perfectly unit tested, and this is particularly straightforward with synchronous notifications, which are the most common kind.

Below we show how to test that synchronous notifications are posted (or not) and validate their userInfo with a little help from the superb Objective-C mocking framework OCMock. Finally, we share a few tips for unit testing observers.

For convenience, the code examples will not use STAssertNoThrow for exception failures.

Testing notification posting

OCMock provides an observer mock. This can be used to test that a particular method posts a particular notification, with the only requirement being knowing the name of the notification. A notification test requires a handful of lines of code:

First we register the observer mock for a specific notification and sender using a category extension provided by OCMock. Then, we tell the mock object to expect the notification from the sender. Since notifications are synchronous by default, right after we call the code that posts the notification we can simply verify the mock object. If the notification was received the observer mock will pass verification, otherwise it will fail.

Finally, like any other observer, once we’re no longer interested in the notification we remove it from `NSNotificationCenter.

Testing unwanted notifications

Some methods might post a notification only if certain conditions are met. A good test suite would also test that the notification is not sent if the conditions are not met. Luckily, the default behavior of the mock observer provided by OCMock is to raise an exception when an unexpected notification is received. The code to test this case is even simpler:

Validating userInfo

When the notification is expected to include specific userInfo keys we should also test that their values are correct. Again, OCMock comes to the rescue:

This is exactly the same than the first unit test example expect for a block that validates the userInfo property, passed using OCMock’s checkWithBlock: method.

Testing the observer

NSNoticationCenter calls observers by a given selector. For unit testing purposes, this selector is part of the public API of the observer class and as such should be included in the test suite.

To test the observer selector we will most likely need to provide it a notification parameter. While NSNotification is not meant to be initialized directly, we can use its static methods notificationWithName:object: and notificationWithName:object:userInfo: to create the notification. Alternatively, we can create a mock notification with OCMock.

Further reading