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