OCMock通知观察者——验证对象

OCMock notification observer - verifying the object

我最近开始使用 OCMock 框架并试图弄清楚如何使用通知观察器。所以在我的源代码中,我观察到一些通知:

typedef enum {
  OperationStatusCompleted,
  // Some other statuses
} SomeOperationStatus;

- (void)addObserverForSomeNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(someOperationStatusDidChange:)
                                               name:@"someOperationStatusDidChange"
                                             object:nil];

- (void)backgroundOperationStatusDidChange:(NSNotification *)notification {
  id<SomeOperationProtocol> operation = [notification object];
  if (operation.status == OperationStatusCompleted) {
    // Do something.
  }
}

现在我想在我的测试中添加对该通知的期望:

- (void)testNotification {
  id observerMock = OCMObserverMock();
  [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:@"someOperationStatusChanged" object:nil];
  [[observerMock expect] notificationWithName:@"someOperationStatusChanged" object:[OCMArg any]];
   // run the test ...
}

它本身工作正常,我在测试中收到了通知,但我真正想检查的是通知对象的 状态(意思是我已收到具有特定状态的特定对象的通知)。可能吗?

我终于知道怎么做了:

[[observerMock expect] notificationWithName:@"someOperationStatusChanged" object:[OCMArg checkWithBlock:^BOOL(id<IMBBackgroundOperation> param) { 
    return param.status == OperationStatusCompleted;
}]];