pixelrevision pixelrevision - 3 months ago 21
iOS Question

Getting Alamofire and OHHTTPStubsWorking together

I am trying to setup OHHTTPStubs to work with Alamofire for my unit tests but they always seem to load from the live network when using Alamofire. I have turned off using a host application in the test target and have made sure that OHHTTPStubs gets used first.

Here is a sample test where the results loaded from Alamofire are from the live network:

import XCTest
import OHHTTPStubs
import Alamofire

@testable import TestAlamoFireStubs

class TestAlamoFireStubsTests: XCTestCase {

let responseText = "{'data':'val'}"

override func setUp() {
super.setUp()
stub(isHost("httpbin.org")) {request -> OHHTTPStubsResponse in
let stubData = self.responseText.dataUsingEncoding(NSUTF8StringEncoding)
return OHHTTPStubsResponse(data:stubData!, statusCode:200, headers:nil)
}
}

func testNSURLSession(){
let expectation = expectationWithDescription("Check NSURLSession")
let url = NSURL(string:"https://httpbin.org/get")
let dataTask = NSURLSession.sharedSession().dataTaskWithURL(url!){ data, response, error in
let responseString = NSString(data:data!, encoding:NSUTF8StringEncoding) as? String
XCTAssertEqual(responseString, self.responseText) // succeeds
expectation.fulfill()
}
dataTask.resume()
waitForExpectationsWithTimeout(10, handler:nil)
}

func testAlamofire() {
let expectation = expectationWithDescription("Check Alamofire")
Alamofire.request(.GET, "https://httpbin.org/get").response{ request, response, data, error in
let responseString = NSString(data:data!, encoding:NSUTF8StringEncoding) as? String
XCTAssertEqual(responseString, self.responseText) // fails
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler:nil)
}
}


And a link to a sample project:
https://www.dropbox.com/s/b0qdvjpk8t6r525/TestAlamoFireStubs.zip

Answer

At least in my particular case I was able to tie Alamofire to OHHTTPStubs by creating custom manager with custom NSURLSession and configuration

import XCTest
import Alamofire
import OHHTTPStubs
@testable import AlamofireOHHTTPStubs

class AlamofireOHHTTPStubsTests: XCTestCase {

    let manager: Manager = {
        let configuration = NSURLSession.sharedSession().configuration

        //The most important string!
        OHHTTPStubs.setEnabled(true, forSessionConfiguration: configuration)

        configuration.URLCache = nil
        let delegate = Manager.SessionDelegate()
        let session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
        return Manager(session: session, delegate: delegate)!
    }()

    let responseText = "{\"data\":\"val\"}"

    func testAlamofireOHHTTPStubs() {
        stub(isHost("httpbin.org")) { request -> OHHTTPStubsResponse in
            let stubData = self.responseText.dataUsingEncoding(NSUTF8StringEncoding)
            return OHHTTPStubsResponse(data:stubData!, statusCode:200, headers:nil)
        }

        let expectation = expectationWithDescription("alamofire request expectation")
        manager.request(.GET, "https://httpbin.org/get").responseJSON { (response) in
            switch response.result {
            case .Success(let json as NSDictionary):
                XCTAssertEqual(json["data"] as? String, "val")
            default:
                XCTFail()
            }
            expectation.fulfill()
        }
        waitForExpectationsWithTimeout(1.0, handler: nil)
    }

}
Comments