如何在XCTest上测试sendAsynchronousRequest :. [英] How to test a sendAsynchronousRequest: on XCTest
问题描述
很抱歉noob问题,但我正在尝试测试连接,但我无法验证请求的返回,因为测试在完成处理程序有机会执行之前结束。说明:
Sorry for the noob question, but I'm trying to test a connection, but I'm not able do verify the return of the request, because the test ends before the completion handler have a chance to execute. To ilustrate:
-(void)testConnection
{
[[Conector sharedInstance] performAsynchronousRequestWithServerRequest:_srvRequest completionHandler:^(RequestAsynchronousStatus finishStatus, NSData *data) {
if (finishStatus == RequestAsynchronousOK){
_data = data;
NSLog(@"Data OK");
}
}];
XCTAssertNotNil(_data, @"Data was nil");
}
当我尝试断言时,_data将始终为零,因为完成处理程序尚未执行。有一种机制可以强制测试等待,直到我从sendAsynchronousRequest:方法得到一些响应。
提前致谢。
When I try to assert, _data will always be nil, because the completion handler wasn't executed yet. There is a mechanism to force the test to wait until I have some response from the sendAsynchronousRequest: method. Thanks in advance.
推荐答案
这看起来就像你需要的那样:
This looks like exactly what you need:
XCAsyncTestCase :具有异步功能的SenTestCase子类。
XCAsyncTestCase: Asynchronous capable SenTestCase subclass.
基本上,你应该像这样编写你的测试:
Basically, you should write your test like this:
- (void)testConnection
{
[[Conector sharedInstance] performAsynchronousRequestWithServerRequest:_srvRequest completionHandler:^(RequestAsynchronousStatus finishStatus, NSData *data) {
if (finishStatus == RequestAsynchronousOK)
{
_data = data;
[self notify:XCTAsyncTestCaseStatusSucceeded];
NSLog(@"Data OK");
}
}];
[self waitForTimeout:10];
XCTAssertNotNil(_data, @"Data was nil");
}
注意 waitForTimeout:
通话和通知:
通话。 10秒应该足以进行测试,但这取决于请求本身。
Notice the waitForTimeout:
call and the notify:
calls. 10 seconds should be enough for the test, though it would depend on the request itself.
你甚至可以更具体地等待某种状态,如下所示: / p>
You could even get more specific and wait for a certain status, like so:
[self waitForStatus: XCTAsyncTestCaseStatusSucceeded timeout:10];
这样,如果连接无法通知 XCTAsyncTestCaseStatusSucceeded
状态,等待调用将超时,您的测试将失败(应该如此)。
This way, if the connection fails to notify the XCTAsyncTestCaseStatusSucceeded
status, the wait call will timeout and your test would fail (as it should).
这篇关于如何在XCTest上测试sendAsynchronousRequest :.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!