A stub for block based data tasks of NSURLSession.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



[![CI Status](http://img.shields.io/travis/Dominik Hauser/DHURLSessionStub.svg?style=flat)](https://travis-ci.org/Dominik Hauser/DHURLSessionStub) Version License Platform


To run the example project, clone the repo, and run pod install from the Example directory first.

Stubbing NSURLSessions Data Task

  1. Import the DHURLSessionStub (import DHURLSessionStub) in the file where you want to use NSURLSession. (In the example project, this is ApiClient.swift.
  2. Use a lazy variable for the session to allow dependency injection in the test: lazy var session: DHURLSession = NSURLSession.sharedSession().
  3. Use dataTaskWithURL and dataTaskWithRequest as you always did.

Then you can stub your data tasks in your tests by assigning a URLSessionMock to the lazy session property you defined in step 2:

func testFetchingProfile_ReturnsPopulatedUser() {
  let responseExpectation = expectationWithDescription("User")
  // Arrage
  let apiClient = APIClient()
  apiClient.session = URLSessionMock(jsonDict: ["login": "dasdom", "id": 1234567])!
  // Act
  var catchedUser: User? = nil
  apiClient.fetchProfileWithName("Foo") { (user, error) in
    catchedUser = user
  // Assert
  waitForExpectationsWithTimeout(1) { (error) in
    let expectedUser = User(name: "dasdom", id: 1234567)
    XCTAssertEqual(catchedUser, expectedUser)

There are two initializers for the URLSessionMock:

public convenience init?(jsonDict: [String : AnyObject], response: NSURLResponse? = default, error: NSError? = default)

public init(data: NSData? = default, response: NSURLResponse? = default, error: NSError? = default)

Have a look at the example project for a complete picture how this is used.

How it works

It's quite easy. The URLSessionMock captures the completion handler of the data task. When the production code calls resume on the data task, the mock then calls the completion handler with the parameters given in the initializer. Have a look! The complete file only has 42 lines of code.


iOS 8.3


DHURLSessionStub is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "DHURLSessionStub"

Alternatively, download DHURLSessionMock and put it into your app target (not the test target!).


Dominik Hauser, dominik.hauser@dasdom.de
Github: dasdom


DHURLSessionStub is available under the MIT license. See the LICENSE file for more info.