Using OCMock to mock [NSNotificationCenter defaultCenter] for isolation and happiness.

NSNotificationCenter defaultCenter is a gross implicit dependency in a lot of code. The reason it is so bad if you are writing tests is because of handling of notifications for things like UIApplicationDidBecomeActiveNotification, where the simulator is going to fire these notifications as it goes through the business of running the application you just launched, but your tests may be already in flight. That example is a little contrived because UIApplicationDidBecomeActiveNotification doesn't often fire during test runs, but let's just move past that.

I like creating and injecting a NSNotificationCenter into my objects under test in order to explicitly allow me to post notifications, test results, etc and not have to worry about the object in my actual running application getting an unexpected notification and to make sure that my object under test doesn't get notifications being posted from the running application. But sometimes you just need to mock the class method [NSNotificationCenter defaultCenter] for the duration of your test and you can get an error saying tests didn't finish when you do this. The solution to this problem is to make sure you call [mockCenter stopMocking] in your test tearDown.

Gist

Comments