A Blog by Josh Adams



Dependency Injection of URLs and URLSessions

Much Benefit

URLSession “and related classes provide an API for downloading data from … endpoints indicated by URLs.” Most iOS developers are familiar with using the URLSession singleton, shared, which has “reasonable default behavior”, including retrieving data from the actual endpoint represented by the URL specified.

But using shared in all circumstances has some drawbacks.

  1. In a production app, during development of a new feature, the endpoint may not exist until late in the development cycle. Using shared means that development of the client-side UI of a new feature is blocked until development of the endpoint is complete.
  2. Because using shared necessarily involves network access, use of shared in unit tests can cause those unit tests to be slow or to fail altogether.
  3. The endpoint may not return the data needed to exercise all functionality of the app. For example, the app may have a special no-data-was-retrieved state, but if the actual endpoint has data, this state can’t be triggered.

This post presents a solution to these three problems: using a stubbed version of URLSession and using alternate URL variants, both via dependency injection.

Paul Hudson described the URLSession-stubbing technique in this excellent article. My post contains two refinements to his article, both described in the section Acknowledgement.

Continue…