2015-02-10 147 views
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调用?

顺便说一句,如果我调试 - 调试程序停止在方法

+0

你在哪里测试调用数? – 2015-02-10 14:36:35

+0

验证(_sut)someMethod:应该测试它至少发生一次 – 2015-02-10 14:37:41

+0

你确定它不应该是'verify([_sut pushReceived:anything()]);'而不是? – 2015-02-10 14:47:09

回答

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 
} 
+0

如果我将_sut注册为通知的侦听器,那么该方法应该测试我的原始视图控制器是否已注册以侦听通知时,它会有什么好处呢! ? – 2015-02-23 09:14:19

相关问题