2012-01-19 141 views
0

我在SenTestCase类中有以下Objective C测试代码。我没有得到任何错误,但httpReceiveDataFinished方法永远不会被调用。这是因为在委托有机会处理http方法之前测试结束了吗?如何使测试方法等待代理完成处理?

如果是这种情况,我该如何分离线程(或类似的东西)以使测试等待几秒钟?

非常感谢任何帮助。我已经编写了Java多年,但Objective-C只有几天。

- (void)testExample 
{ 
    HttpClient *client = [[HttpClient alloc] init]; 
    client.method = METHOD_GET; 
    client.followRedirects = YES; 
    [client processRequest:@"http://google.com" delegate:self]; 
    NSLog(@"Test Over"); 
} 

-(void) httpReceiveError:(NSError*)error { 
    NSLog(@"***\n%@\n***",[error description]); 
} 

- (void) httpReceiveDataChunk:(NSData *)data { 
    [self.httpResponseData appendData:data]; 
} 

-(void) httpReceiveDataFinished { 
    NSString *result = [[NSString alloc] 
     initWithData:self.httpResponseData 
     encoding:NSUTF8StringEncoding]; 
    NSLog(@"***\nRESULT: %@ \n***",result); 
} 
+2

http://stackoverflow.com/questions/1077737/ocunit-test-for-protocols-callbacks-delegate-in-objective-c –

+0

真棒。像魅力一样工作。 –

回答

0

第一:斯坦尼斯拉夫的联系非常好。 对于我自己,我需要一些更灵活的东西(长时间运行),但也会在成功时立即通过测试。 (大文件下载等)

这是我的效用函数:

-(BOOL)runLooperDooper:(NSTimeInterval)timeoutInSeconds 
     optionalTestName:(NSString *)testName 
{ 
    NSDate* giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; 
    // loop until the operation completes and sets stopRunLoop = TRUE 
    // or until the timeout has expired 

    while (!stopRunLoop && [giveUpDate timeIntervalSinceNow] > 0) 
    { 
     // run the current run loop for 1.0 second(s) to give the operation code a chance to work 
     NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:1.0]; 
     [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; 
    } 

    STAssertTrue(stopRunLoop, 
       @"%@ failed to finish before runloop expired after %f seconds", testName, timeoutInSeconds); 
    return stopRunLoop; 
} 

声明stopRunLoop在你的测试类伊娃。确保在您的setUp函数中将stopRunLoop重置为FALSE,然后在调用您的[client processRequest:@"http://google.com" delegate:self];之前调用此函数。然后,在您的事件处理函数中,将stopRunLoop设置为TRUE。

通过传递一个testName,您可以重复使用它进行多个测试并获取一些有意义的错误消息。

编辑:99%肯定我基于上述代码关闭另一个StackOverflow帖子,目前我找不到,或者我会链接它。