Latest 0.1.0
License MIT
Platforms ios 8.0, requires ARC

[![CI Status]( Hauser/DHURLSessionStub.svg?style=flat)]( Hauser/DHURLSessionStub)


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() {
  // Arrage
  let responseString = "{"login": "dasdom", "id": 1234567}"
  let responseData = responseString.dataUsingEncoding(NSUTF8StringEncoding)!
  let sessionMock = URLSessionMock(data: responseData, response: nil, error: nil)
  apiClient.session = sessionMock

  // Act

  // Assert
  let user = apiClient.user
  let expectedUser = User(name: "dasdom", id: 1234567)
  XCTAssertEqual(user, expectedUser)

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

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, [email protected]


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

Latest podspec

    "name": "DHURLSessionStub",
    "version": "0.1.0",
    "summary": "A stub for block based data tasks of NSURLSession.",
    "description": "This pod helps you to write easy unit test stubs for NSURLSession data tasks. At the moment it only supports the block bases API of NSURLSesssion because this is what I use in 95% of the cases. This is useful for example when you want to implement the API client of your app befor the server side is finished or if you want to test the networking of your app without internet connection.",
    "homepage": "",
    "license": "MIT",
    "authors": {
        "Dominik Hauser": "[email protected]"
    "source": {
        "git": "",
        "tag": "0.1.0"
    "social_media_url": "",
    "platforms": {
        "ios": "8.0"
    "requires_arc": true,
    "source_files": "Pod/Classes/**/*",
    "resource_bundles": {
        "DHURLSessionStub": [

Pin It on Pinterest

Share This