1

所以我需要测试是否NSNotification发布了 a 。我尝试了以下代码来监视参数。

[[NSNotificationCenter defaultCenter] stub:@selector(postNotification:)];

__block KWCaptureSpy *notificationSpy = [[NSNotificationCenter 
defaultCenter] captureArgument:@selector(postNotification:) atIndex:0];

[[theValue(notificationSpy.argument.name) should] equal:theValue(SOME_NOTIFICATION)];

但是这个问题是因为它是异步的,所以在测试之前并不总是捕获参数。我也无法添加shouldEventuallynotificationSpy.argument.name,因为它会NSInternalConsistencyException在捕获之前访问参数。

我也试过了, [[SOME_NOTIFICATION should] bePosted]; 也失败了。

4

2 回答 2

3

如果您希望在未来某个时间发送通知,则可以使用expectFutureValue() :

[[expectFutureValue(((NSNotification*)notificationSpy.argument).name) shouldEventually] equal:@"MyNotification"];

您也不会遇到NSInternalConsistencyException异常,因为如果将 Kiwi 包裹在expectFutureValue.

其他选择是

  • stubsendNotification:方法和“手动”捕获发送的通知:

    __block NSString *notifName = nil;
    [[NSNotificationCenter defaultCenter] stub:@selector(postNotification:) withBlock:^id(NSArray *params) {
        NSNotification *notification = params[0];
        notifName = notification.name;
        return nil;
    }];
    [[notifName shouldEventually] equal:@"TestNotification"];
    
  • 编写一个注册到通知中心的自定义匹配器并在该匹配器上断言:

    [[[NSNotificationCenter defaultCenter] shouldEventually] sendNotification:@"MyNotification"]];
    

就个人而言,我会使用自定义匹配器方法,它更优雅、更灵活。

于 2015-05-19T09:14:13.233 回答
2

我可能会遗漏一些上下文,因为您没有解释正在测试的代码。你在发通知吗?或者您是否试图断言 IOS 框架会为您发布通知?无论如何,以下是我在您的方法中看到的问题:

  1. 您需要在监视 postNotification 选择器之后并在断言 spied 参数的值之前运行发布通知的操作。从您发布的代码中,尚不清楚这是否正在发生。

  2. 如果确实调用了 postNotification 方法,则此解决方案应该有效。我实际上不认为这是一个异步问题。我经常在 defaultCenter 上成功监视 postNotificationName:object:userInfo: 并且没有特殊的异步处理代码。

  3. 为了在 Kiwi 中检查字符串的相等性,不要将它们包装在 theValue() 中。theValue() 用于检查标量属性的相等性。你的断言应该是这样的:

    [[((NSNotification*)notificationSpy.argument).name should] equal:@"myNotificationName"];
    

如果这不能帮助您获得解决方案,请提供更多您正在测试的方法的代码和完整的测试方法,以及任何其他有用的信息。

于 2015-05-18T01:26:51.557 回答