2

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

4

3 回答 3

4

至少在我的特定情况下,我能够通过使用自定义 NSURLSession 和配置创建自定义管理器来将 Alamofire 绑定到 OHHTTPStubs

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)
    }

}
于 2016-04-21T17:23:55.270 回答
1

对我来说,问题是我的 Podfile 丢失了pod 'OHHTTPStubs',我只pod 'OHHTTPStubs/Swift'在那里。正确的 Podfile 应该如下所示:

pod 'OHHTTPStubs'  # This one required!!
pod 'OHHTTPStubs/Swift'  # This one optional

所有这些都记录在OHTTPStubs README中。

于 2016-09-01T06:24:14.963 回答
0

如果有人想知道如何在 Alamofire 4 和 Swift 3 中设置自定义管理器,这里是解决方案:

let sessionManager: SessionManager

init() {
    let configuration = URLSessionConfiguration.default

    OHHTTPStubs.setEnabled(true, for: configuration)

    configuration.urlCache = nil

    sessionManager = SessionManager(configuration: configuration)
}
于 2017-07-24T10:56:24.367 回答