【问题标题】:How can I wait for my asynchronous Kiwi tests to complete, or run code after they do?如何等待我的异步 Kiwi 测试完成,或在完成后运行代码?
【发布时间】:2015-07-28 01:22:39
【问题描述】:

我正在使用 Kiwi 进行一些异步测试。一项测试检查,在(存根)网络请求之后,来自网络的响应是否写入磁盘。网络请求和将响应写入磁盘都是在后台队列中完成的:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    [[HZMediationAPIClient sharedClient] GET:@"start" parameters:nil success:^(HZAFHTTPRequestOperation *operation, NSDictionary *json) {

        // store JSON to disk
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            [json writeToURL:[[self class] pathToStartInfo] atomically:YES];
        });

        [self.delegate startWithDictionary:json fromCache:NO];

    } failure:^(HZAFHTTPRequestOperation *operation, NSError *error) {

    }];
});

我可以使用 Kiwi 的异步测试功能来测试接收startWithDicationary:fromCache 方法的委托:

[[expectFutureValue(starterMock) shouldEventually] receive:@selector(startWithDictionary:fromCache:) withArguments:json,theValue(NO)];

但是,我不确定如何测试数据是否正确写入磁盘。在将数据写入磁盘后,我可以执行类似发送委托方法的操作,然后测试是否会发生这种情况:

[[expectFutureValue(starterMock) shouldEventually] receive:@selector(wroteDictionaryToCache)];

但即使我验证消息已发送,我也无法检查数据是否实际写入磁盘。

it(@"Returns the data from network when no cached value, then updates the cache", ^{
    // ... test setup here

    [[expectFutureValue(starterMock) shouldEventually] receive:@selector(wroteDictionaryToCache)]; // This code finishes immediately
    // Code here checking if the data has been written to disk will be executed before the above expectations become true.
});

有没有一种方法可以等待异步期望通过/失败,然后我可以测试数据是否写入磁盘?或者我可以在期望中附加一个完成块,以便在这些异步期望通过/失败时编写未来的测试?

如果您有其他方法来测试它,那也很好。

【问题讨论】:

    标签: ios unit-testing asynchronous kiwi


    【解决方案1】:

    我没有想出一种方法来完全做到这一点,但我得出结论,为了测试目的,将缓存逻辑移出一个单独的对象并使其成为我正在测试的类的依赖项会更好。其界面如下所示:

    @interface HZCachingService : NSObject
    
    - (void)cacheDictionary:(NSDictionary *)dictionary filename:(NSString *)filename;
    - (NSDictionary *)dictionaryWithFilename:(NSString *)filename;
    
    @end
    

    我只是将该对象传递给我在其init 方法中测试的类。在测试中,我存根该对象并验证 cacheDictionary:filename: 是否使用正确的参数对其进行了调用。

    我在单独的规范中测试了HZCachingService 的实际写入磁盘行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 2014-04-03
      • 2015-07-01
      • 1970-01-01
      相关资源
      最近更新 更多