Wil*_*ris 22 iphone cocoa-touch objective-c ocmock
我正在编写一个需要从Web服务器获取一些数据的iPhone应用程序.我正在使用NSURLConnectionHTTP请求,这很有效,但在响应有HTTP错误代码(如404或500)的情况下,我无法对代码进行单元测试.
当服务器返回一个错误,该连接不会调用connection:didFailWithError:的委托,但呼吁connection:didReceiveResponse:,connection:didReceiveData:以及connectionDidFinishLoading:代替.我正在检查响应中的状态代码connection:didReceiveResponse:并cancel在状态代码看起来像一个错误时调用连接以防止connectionDidFinishLoading:被调用,其中将报告成功的响应.
提供静态存根NSURLConnection很简单,但我希望我的测试在调用其中一个模拟连接的方法时改变它的行为.具体来说,我希望测试能够告诉代码何时调用cancel模拟连接,因此测试可以停止调用connection:didReceiveData:和connectionDidFinishLoading:代理.
有没有办法让测试判断是否cancel已经在模拟对象上调用了?有没有更好的方法来测试使用的代码NSURLConnection?有没有更好的方法来处理HTTP错误状态?
e.J*_*mes 43
有没有更好的方法来处理HTTP错误状态?
我认为你走在正确的轨道上.我使用类似于以下代码的东西,我在这里找到:
if ([response respondsToSelector:@selector(statusCode)])
{
int statusCode = [((NSHTTPURLResponse *)response) statusCode];
if (statusCode >= 400)
{
[connection cancel]; // stop connecting; no more delegate messages
NSDictionary *errorInfo
= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:
NSLocalizedString(@"Server returned status code %d",@""),
statusCode]
forKey:NSLocalizedDescriptionKey];
NSError *statusError
= [NSError errorWithDomain:NSHTTPPropertyStatusCodeKey
code:statusCode
userInfo:errorInfo];
[self connection:connection didFailWithError:statusError];
}
}
Run Code Online (Sandbox Code Playgroud)
这将取消连接,并调用connection:didFailWithError:以使http错误代码与任何其他连接错误完全相同.
| 归档时间: |
|
| 查看次数: |
16746 次 |
| 最近记录: |