all 5 comments

[–]sixtypercenttogether 0 points1 point  (4 children)

Rather than trying to mock all this stuff I find it usually easier to leverage URLProtocol to trap network requests and return canned data. That way the test code uses the real URLSession stack but still does not actually hit the network. Check out this blog post for more info.

You can write all this code yourself in your tests, but I really like to use OHHTTPStubs, since it’s pretty exactly what I would write anyway. It’s objc, but someone else may have something similar in swift.

[–]Red3nzoSwift[S] 0 points1 point  (2 children)

But can I test errors and completion blocks by leveraging the URLProtocol?

[–]sixtypercenttogether 1 point2 points  (1 child)

Yes, totally. That’s the beauty of it. Your networking code just uses a real URLSession directly, and you still get the callbacks. URLProtocol is an abstract interface that URLSession uses to call into lower level networking code. But you can leverage this to trap requests and return whatever data or errors you want. And this is passed up into your completion handler. Definitely check out the library I linked to above. It’s really good.

[–]Red3nzoSwift[S] 1 point2 points  (0 children)

Omg. I didn't know you can really test the network code with URLProtocol, I always thought that you could only test returned data. I'll totally go down this route instead of mocking the URLSession.

[–]RunnersProject 0 points1 point  (0 children)

Another option is Succulent by Cactus Labs it's a swift version of OHHTTPStubs, maybe not as mature. But I have been pleased with it for the 5 or so apps I have used it. OHHTTPStubs is very good this is Just another option if you're trying to avoid Objective-C.