1

I'm setting up Unit tests for my project in Xcode 5. In a unit test, I trigger some events that will build and send an HTTP request to a server. Even though I see the request being sent and receiving a response (through Charles Web Proxy), it doesn't appear that any code from the NSURLConnectionDelegate or NSURLConnectionDataDelegate are executing, such as

– connection:didReceiveResponse:
– connection:didReceiveData:

I know there are already plenty of questions on unit testing asynchronous code but I'm concerned with why my HTTP request gets sent and receives response but my delegate doesn't execute callbacks during unit tests. I've ensured that the test isn't finishing execution before the async operation has time to complete.

Thanks.

mbradber
  • 489
  • 5
  • 17
  • 2
    A possible reason could be that your delegates are scheduled on the Run Loop associated to the _main thread_ (which is the default), and your test method will also execute on the main thread - a classic dead lock. You can fix that with explicitly invoking a run loop, though there are a couple of subtleties to consider. – CouchDeveloper Feb 27 '14 at 00:28
  • Cool that makes sense, thanks. Put this as an answer and I'll select it. – mbradber Feb 27 '14 at 01:00
  • What do you mean by "promises"? – mbradber Feb 27 '14 at 01:05
  • ohps - wrong comment ... :) I was referring to this question: http://stackoverflow.com/questions/22055279/how-to-test-async-code-using-xctestcase#comment33444948_22055279 You can certainly check if the link in my comment does help you as well ;) – CouchDeveloper Feb 27 '14 at 01:08

1 Answers1

0

Wrap your network code with some helper methods and mock it. You don't want to hit the network in your unit tests because:

a) it'll slow down your unit tests

b) it'll introduce instability (eg: network or server goes down)

In general you want your unit tests to be repeatable and introducing network into the equation is just going to cause you headaches. Obtain an example of what some good content looks like, and some bad content (eg: a 404 error, or other situations your app might encounter). Put those data files into your unit test project and then have your faked network code return the data files instead of making the network requests.

Nicholas Hart
  • 1,734
  • 13
  • 22
  • Thanks Nicholas. I was asking this more from a technical curiosity, I've read plenty about how you shouldn't do this. Just want to know why these delegate callbacks don't execute when run from a unit test, even though the request goes through while the test is running. – mbradber Feb 26 '14 at 23:26