1

我想测试某个方法被调用以响应收到的 NSNotification

我试过这个:

_sut = mock([EAMainScreenViewController class]);
[_sut view];
[[NSNotificationCenter defaultCenter]postNotificationName:kNotificationPushReceived object:[UIApplication sharedApplication].delegate userInfo:nil];
[verify(_sut) pushReceived:anything()];

我的 _sut viewDidLoad 看起来像这样

- (void)viewDidLoad {
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushReceived:) name:kNotificationPushReceived object:[UIApplication sharedApplication].delegate];
}

为什么我的测试在预期 1 次调用和接收 0 次调用时失败?

顺便说一句,如果我调试 - 调试器确实停止在该方法

4

1 回答 1

0

你应该重写你的测试到下一个:

- (void)setUp {
    _sut = [[EAMainScreenViewController alloc] <properInit>];
}

- (void)tearDown {
    //just in case
    [[NSNotificationCenter defaultCenter] removeObserver:_sut];
}

- (void)testThatNotificationPushReceived {
    [_sut viewDidLoad];

    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationPushReceived object:<probably some mock> userInfo:nil];

    //test something that happens with your mock
}
于 2015-02-23T09:09:48.447 回答