为什么OCMock在使用mockObserver时会导致nsnotificaiton中心拥有EXC_BAD_ACCESS

Inf*_*rid 2 ocmock

我设置了这样的模拟观察者:

id quartileObserverMock = [OCMockObject observerMock];
[[NSNotificationCenter defaultCenter] addMockObserver:quartileObserverMock
                                                 name:kVPAdPlayerDidReachQuartileNotification
                                               object:self.adPlayer];

[[quartileObserverMock expect]
                       notificationWithName:kVPAdPlayerDidReachQuartileNotification
                                     object:self.adPlayer
                                   userInfo:@{@"quartile" : @(VPAdPlayerFirstQuartile), @"trackingEvent" : VPCreativeTrackingEventFirstQuartile}];
Run Code Online (Sandbox Code Playgroud)

我的单元测试运行; 但是当发布通知时,我得到虚假的EXC_BAD_ACCESS错误.

[[NSNotificationCenter defaultCenter]
                           postNotificationName:kVPAdPlayerDidReachQuartileNotification
                                         object:self.adPlayer
                                       userInfo:@{@"quartile" : @(quartile), @"trackingEvent" : trackingEvent}];
Run Code Online (Sandbox Code Playgroud)

当我注释掉observermock代码时,我的测试每次运行都很好.

当我重新放入代码时,我会在postNotiicaitonName:object:userInfo上发生虚假崩溃,可能每2.5次一次.

有人有任何想法吗?

Pra*_*iga 8

请参阅以下示例代码,这可能对您有所帮助.它对我有用

- (void)test__postNotificationwithName__withUserInfo
{
     id observerMock  = [OCMockObject observerMock];
     [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:@"NewNotification" object:nil];

     NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:@"2",@"2", nil];
     [[observerMock expect] notificationWithName:@"NewNotification" object:[OCMArg any] userInfo:userInfo];

     NotificationClass *sut = [[NotificationClass alloc] init];
     [sut postNotificationwithName:@"NewNotification" userInfo:userInfo];

     [[NSNotificationCenter defaultCenter] removeObserver:observerMock];
     [observerMock verify];
}
Run Code Online (Sandbox Code Playgroud)

和我的发布通知方法

- (void)postNotificationwithName:(NSString *)notifName userInfo:(NSDictionary *)userInfo
{
     [[NSNotificationCenter defaultCenter] postNotificationName:notifName object:self userInfo:userInfo];
}
Run Code Online (Sandbox Code Playgroud)

请注意:

  1. 当收到意外通知时,observerMock总是引发异常.
  2. 在测试用例结束时从NSNotificationCenter中删除模拟的观察者.