observerMock and distributed notifications

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.

observerMock and distributed notifications

Postby ander833 » 16 Dec 2009, 22:44

I try to use [OCMock observerMock] to verify that a distributed notification is sent, but without any luck.

The issue seems to be the use of [NSDistibutedNotificationCenter defaultCenter] since the test works fine if I change the notification center to [NSNotificationCenter defaultCenter].

Is observerMock supposed to work with distributed notifications, or am I doing something wrong?

This is my test:
Code: Select all
   NSNotificationCenter* center = [NSDistributedNotificationCenter defaultCenter];
   id mockObserver = [OCMockObject observerMock];
   [center addMockObserver:mockObserver name:@"foo" object:nil];   
   [[mockObserver expect] notificationWithName:@"foo" object:nil];   
   [center postNotificationName:@"foo" object:nil];
   [mockObserver verify];
   [center removeObserver:mockObserver];


The error that I get is:
OCMockObserver: expected notification was not observed: <OCMObserverRecorder: 0x1336e900>
ander833
 
Posts: 3
Joined: 16 Dec 2009, 22:35

Re: observerMock and distributed notifications

Postby erik » 17 Dec 2009, 05:13

I can't verify this right now but it is likely that the notifications to the distributed notification centre are delivered asynchronously, ie. the notification will not be delivered during the call to postNotificationName: but at some later point; in this test case likely after the verify.

In a Cocoa application there is a way to yield to the run loop event processing but I doubt this'll work in the unit test rig. Alternatively, there might be a way to force synchronous posting of the notification. Maybe you could inject the notification centre into the object that posts the notification, then during the tests you could use a normal centre with synchronous delivery and in the real app you could use the distributed one.
erik
 
Posts: 71
Joined: 10 Oct 2009, 15:22
Location: Hamburg, Germany

Re: observerMock and distributed notifications

Postby ander833 » 17 Dec 2009, 22:57

Yes, that would make sense.

I ended up doing what you suggested and replace the distributed center with a normal one. Works fine, but made the code a bit more complex.

Thanks for the help!
ander833
 
Posts: 3
Joined: 16 Dec 2009, 22:35

Re: observerMock and distributed notifications

Postby erik » 17 May 2010, 07:17

Turns out you can actually yield to the run loop in unit tests. This blog post explains how do it:

http://touchalicious.com/blog/2009/11/5/asynchronous-unit-testing-with-ocmock.html
erik
 
Posts: 71
Joined: 10 Oct 2009, 15:22
Location: Hamburg, Germany


Return to OCMock



cron