我如何等待我的异步Kiwi测试完成,或者在他们执行后运行代码?

时间:2015-07-28 01:22:39

标签: ios unit-testing asynchronous kiwi

我正在使用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.
});

有没有办法可以等待异步期望通过/失败,以便我可以测试数据是否写入磁盘?或者我可以将完成块附加到期望值上,以便在异步期望通过/失败时编写未来的测试吗?

如果你有另一种测试方法,那也很好。

1 个答案:

答案 0 :(得分:0)

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

@interface HZCachingService : NSObject

- (void)cacheDictionary:(NSDictionary *)dictionary filename:(NSString *)filename;
- (NSDictionary *)dictionaryWithFilename:(NSString *)filename;

@end

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

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