OCMock通知观察者 - 验证对象

时间:2018-06-14 08:12:43

标签: objective-c unit-testing ocmock

我最近开始使用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 ...
}

这本身工作正常并且我在测试中收到通知但我真正要检查的是通知对象的状态(这意味着我收到了通知具有特定状态的特定对象)。有可能吗?

1 个答案:

答案 0 :(得分:0)

我终于想出了如何做到这一点:

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