AliSoftware / OHHTTPStubs

Stub your network requests easily! Test your apps with fake network data and custom response time, response code and headers!
MIT License
5.04k stars 601 forks source link

Duplicate request when test passes #197

Closed markedwards closed 8 years ago

markedwards commented 8 years ago

Using both 5.1.0 and 5.2.0, when YES is returned from the test in stubRequestsPassingTest:withStubResponse:, I see a duplicate request passed to the test. If NO is returned, this does not occur. By duplicate, I mean the exact same request object is passed to the test a second time.

This seems to be due to two calls to the firstStubPassingTestForRequest: method in OHHTTPStubs.m. Is this the intended behavior? It seems like it should be unnecessary to run every test twice.

AliSoftware commented 8 years ago

Yes sadly it's a drawback from how NSURLProtocol is used in the Cocoa URL Loading system, calling the protocol's canInitWithRequest: of the protocol twice sometimes (depending on iOS version) for some reasons. I have no control over it because that's a method called by the OS itself twice that triggers this double call so no real way to avoid this properly.

That's also a reason why I did a refactor the API some major versions ago — before the current API, the old one only took one block/closure and stubbed the request only if you returned non-nil response, but the fact that the methods was called many times by the OS made your potentially expensive code in that closure (maybe reading the content to sub from a file for example) run multiple times :-/ . That's another reason why those two closures (the one for testing and the one for building the response) are now separate.

I've filed a bug report to Apple years ago about that behavior but no response so far.

AliSoftware commented 8 years ago

See also the release notes from version 2.0.0 where I made that API change 3 years ago mainly because of that issue.

https://github.com/AliSoftware/OHHTTPStubs/releases/tag/2.0.0

markedwards commented 8 years ago

:-(

Thanks for the explanation!