[![CI Status](http://img.shields.io/travis/Dominik Hauser/DHURLSessionStub.svg?style=flat)](https://travis-ci.org/Dominik Hauser/DHURLSessionStub)
To run the example project, clone the repo, and run pod install
from the Example directory first.
- Import the DHURLSessionStub (
import DHURLSessionStub
) in the file where you want to useNSURLSession
. (In the example project, this isApiClient.swift
. - Use a lazy variable for the session to allow dependency injection in the test:
lazy var session: DHURLSession = NSURLSession.sharedSession()
. - Use
dataTaskWithURL
anddataTaskWithRequest
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
responseExpectation.fulfill()
}
// 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.
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
@dasdom
Github: dasdom
swiftandpainless.com
DHURLSessionStub is available under the MIT license. See the LICENSE file for more info.