我看到其他帖子提供了解决此问题的方案。然而,它们的解决方案需要将hacky代码添加到我的应用程序中以便进行测试。对我来说,干净的代码比单元测试更重要。
我经常在我的应用程序中使用dispatch_async,但是我无法对其进行单元测试。问题是该块在主队列上异步运行,因此在测试完成之后才执行。是否有一种方法可以等待块被执行然后才继续测试。
我不想仅因为进行单元测试而向块传递完成处理程序
- (viod)viewDidLoad
{
[super viewDidLoad];
// Test passes on this
[self.serviceClient fetchDataForUserId:self.userId];
// Test fails on this because it's asynchronous
dispatch_async(dispatch_get_main_queue(), ^{
[self.serviceClient fetchDataForUserId:self.userId];
});
}
- (void)testShouldFetchUserDataUsingCorrectId
{
static NSString *userId = @"sdfsdfsdfsdf";
self.viewController.userId = userId;
self.viewController.serviceClient = [[OCMockObject niceMockForClass:[ServiceClient class]];
[[(OCMockObject *)self.viewController.serviceClient expect] fetchDataForUserId:userId];
[self.viewController view];
[(OCMockObject *)self.viewController.serviceClient verify];
}