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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…