2012-01-19 138 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帖子,目前我找不到,或者我會鏈接它。