测试 NSURLConnection 与 HTTP 响应错误状态的使用
我正在编写一个 iPhone 应用程序,需要从 Web 服务器获取一些数据。 我正在使用 NSURLConnection 来执行 HTTP 请求,效果很好,但在响应具有 HTTP 错误代码(如 404 或 500)的情况下,我在单元测试我的代码时遇到了麻烦。
当服务器返回错误时,连接不会在委托上调用connection:didFailWithError:
,而是调用connection:didReceiveResponse:
、connection:didReceiveData:
code> 和 connectionDidFinishLoading:
代替。 我目前正在检查 connection:didReceiveResponse:
中响应的状态代码,并在状态代码看起来像是错误时在连接上调用 cancel
以防止 connectionDidFinishLoading :
被调用,将报告成功的响应。
提供静态存根 NSURLConnection
很简单,但我希望我的测试在调用模拟连接的方法之一时更改其行为。 具体来说,我希望测试能够判断代码何时在模拟连接上调用了 cancel
,因此测试可以停止调用 connection:didReceiveData:
和 connectionDidFinishLoading:
在委托上。
有没有办法让测试判断是否已在模拟对象上调用了 cancel
? 有没有更好的方法来测试使用 NSURLConnection
的代码? 有没有更好的方法来处理 HTTP 错误状态?
I'm writing an iPhone application that needs to get some data from a web server. I'm using NSURLConnection
to do the HTTP request, which works well, but I'm having trouble unit testing my code in the case where the response has an HTTP error code (like 404 or 500).
I'm using GTM for unit testing and OCMock for mocking.
When the server returns an error, the connection does not call connection:didFailWithError:
on the delegate, but calls connection:didReceiveResponse:
, connection:didReceiveData:
, and connectionDidFinishLoading:
instead. I'm currently checking the status code on the response in connection:didReceiveResponse:
and calling cancel
on the connection when the status code looks like an error to prevent connectionDidFinishLoading:
from being called, where a successful response would be reported.
Providing a static stubbed NSURLConnection
is simple, but I want my test to change it's behaviour when one of the mock connection's methods is called. Specifically, I want the test to be able to tell when the code has called cancel
on the mock connection, so the test can stop calling connection:didReceiveData:
and connectionDidFinishLoading:
on the delegate.
Is there a way for tests to tell if cancel
has been called on the mock object? Is there a better way to test code that uses NSURLConnection
? Is there a better way to handle HTTP error statuses?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你走在正确的道路上。 我使用类似于以下代码的代码,我在此处找到了
该代码:这会取消连接,并调用
connection:didFailWithError:
以使 http 错误代码的行为与任何其他连接错误完全相同。I think you are on the right track. I use something similar to the following code, which I found here:
This cancels the connection, and calls
connection:didFailWithError:
in order to make http error codes behave exactly the same as any other connection error.