我有一个单元测试,我需要等待异步任务完成。我正在尝试使用 NSConditionLock,因为它似乎是一个非常干净的解决方案,但我无法让它工作。
一些测试代码:
- (void)testSuccess
{
loginLock = [[NSConditionLock alloc] init];
Login login = [[Login alloc] init];
login.delegate = self;
// The login method will make an async call.
// I have setup myself as the delegate.
// I would like to wait to the delegate method to get called
// before my test finishes
[login login];
// try to lock to wait for delegate to get called
[loginLock lockWhenCondition:1];
// At this point I can do some verification
NSLog(@"Done running login test");
}
// delegate method that gets called after login success
- (void) loginSuccess {
NSLog(@"login success");
// Cool the delegate was called this should let the test continue
[loginLock unlockWithCondition:1];
}
我试图在这里遵循解决方案: 如何对异步 API 进行单元测试?
如果我锁定,我的代表永远不会被调用。如果我取出锁码并放入一个简单的计时器,它就可以正常工作。
我是否锁定了整个线程并且不让登录代码运行并实际进行异步调用?
我也尝试过将登录调用放在不同的线程上,这样它就不会被锁定。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
[login login];
});
我究竟做错了什么?
编辑添加登录代码。为了可读性,修剪了代码。基本上只需使用 AFNetworking 来执行 POST。完成后将调用委托方法。登录发出http请求:
NSString *url = [NSString stringWithFormat:@"%@/%@", [_baseURL absoluteString], @"api/login"];
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (_delegate) {
[_delegate loginSuccess];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (_delegate) {
[_delegate loginFailure];
}
}];