如何验证方法被调用



我想测试在收到的NSNotification时调用的某个方法

我试过这个:

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

我的输出视图DidLoad看起来像这个(_S)

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

为什么我的测试在预期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
}

最新更新