提问人:FranticRock 提问时间:7/9/2016 最后编辑:CommunityFranticRock 更新时间:7/9/2016 访问量:3284
XCTest:NSURLSession:主线程上的停滞
XCTest: NSURLSession: Stall on main thread
问:
运行执行网络操作的 XCTest 时,出现以下错误:
-waitForExpectationsWithTimeout:超时,但无法运行超时处理程序,因为主线程无响应(等待超时后允许 0.5 秒)。可能导致这种情况的情况包括主线程上的处理阻塞 IO、对 sleep() 的调用、死锁和同步 IPC。Xcode 将尝试重新启动该过程并继续下一次测试...
我有一个测试,它执行一个网络命令方法,该方法在后台使用 NSURLSession。
此测试是具有 4 个连续网络请求测试的测试类的一部分。
当独立于其他测试运行时,它每次都会成功。 运行整个测试文件(总共 4 个测试)时,每次都成功。
但是当运行整个测试套件(50 个测试)时,我在第一次网络操作测试中出现“主线程失速”。其他 3 项网络操作测试通过良好。
以下是测试的代码:
- (void)test_session_001_ObtainsSessionObjectFromServer
{
XCTestExpectation *expectation = [self expectationWithDescription:[self description]];
id<IPVideoSessionProtocol> provider = [IPVideoSessionFactory getProvider];
[provider createVideoSessionWithUserID:@"SomeUserID"
withCompletionBlock:^(IPVideoSession *session) {
if ([session isKindOfClass:[IPVideoSession class]] &&
[session.sessionID isKindOfClass:[NSString class]] &&
session.sessionID.length > 0) {
// The returned session ID is populated
[expectation fulfill];
}
}];
[self waitForExpectationsWithTimeout:5.0f handler:^(NSError *error) {
if (error)
{
XCTFail(@"IPVideoSessionManagerTests Did not execute in allotted time");
}
}];
}
createVideoSession中的代码...
- (void)createVideoSessionWithUserID:(NSString*)userID
withCompletionBlock:(IPVideoSessionCompletionBlock)block
{
IPCreateVideoSessionCommand* command = [[IPCreateVideoSessionCommand alloc]
initWithUserID:userID];
[command executeWithCompletionBlock:^(IPNetworkError *error, NSString *resultJSON)
{
if (error) {
[IPAlertPresenter displayNetworkError:error];
block(nil);
return;
}
NSDictionary *dict = [resultJSON toJsonDictionary];
block([IPVideoSession getSessionFromDictionary:dict]);
}];
}
executeWithCompletionBlock 中的代码:
- (void)executeWithCompletionBlock:(CommandCompletionBlock)block
{
if (!self.isConnected && ![[IPDebugManager sharedInstance] networkBypassActivated]) {
IPNetworkError* error = [[IPNetworkError alloc] initWithType:NetworkErrorTypeNotConnectedToNetwork];
block(error, nil);
return;
}
NSURLSession *session = [self composeSession];
NSURLRequest *request = [self composeRequest];
self.strongSelf = self;
__weak __typeof(self) weakSelf = self;
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[IPDispatch toMainThread:^{
[weakSelf
handleCommandResponse:response
withData:data
withError:error
withCompletionBlock:block];
weakSelf.strongSelf = nil;
}];
}];
[dataTask resume];
}
注意:仅当运行所有测试时,才会发生此错误。这个测试本身就成功了,而且:如果我在这个测试类中运行所有 4 个测试。
答: 暂无答案
评论