使用OHHTTPStubs进行模拟时未达到Alamofire响应阻止

时间:2018-06-06 13:51:36

标签: ios swift alamofire ohhttpstubs

当我运行应用程序时,Alamofire响应阻止就没问题了。当运行测试并使用OHHTTPStub模拟响应时,将调用存根块(请求和响应),但从不调用Alamofire响应块,因此测试失败。 尝试使用URLRequest完全相同的存根,并且响应块被称为没有问题。

Api课程:

private static var config: URLSessionConfiguration?
private static var session: SessionManager?

static var instance = getInstance()

private static func getInstance() -> Api {
    let api = self.init()
    return api
}

private init() {
    Api.config = URLSession.shared.configuration
    var headers = SessionManager.defaultHTTPHeaders
    headers.removeValue(forKey: "User-Agent")
    headers["User-Agent"] = APP_VERSION
    Api.config?.httpAdditionalHeaders = headers
    Api.session = SessionManager(configuration: Api.config!)
}

func requestFunction(_ path: String) {
    let req = Api.session!.request("\(apiUrl())\(path)", method: .get, parameters: request.toJSON()).response(completionHandler: completionHandler)
}

测试:

func test() {
    stub(condition: { (request) -> Bool in
            return true
        }) { (request) -> OHHTTPStubsResponse in
            return OHHTTPStubsResponse(
                jsonObject: self.usageResponse,
                statusCode: 200,
                headers: ["Content-Type":"application/json"]
            )
        }

    let semaphore = DispatchSemaphore.init(value: 0)
    Api.instance.requestFunction(path, { (_, _) in
        semaphore.signal()
    })

    let timeout = DispatchTime.now() + DispatchTimeInterval.seconds(300)
    if semaphore.wait(timeout: timeout) == DispatchTimeoutResult.timedOut {
        XCTFail("semaphore not reached")
    }
}

从未到达信号量。但是,如果不是调用Alamofire我这样做,信号量就没有问题了:

    do {
        let request = try URLRequest.init(url: "www.w.com", method: .post)
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        let task = session.dataTask(with: request) { (_, _, _) in
            semaphore.signal()
        }
        task.resume()
    } catch {

    }

1 个答案:

答案 0 :(得分:0)

不确定是否曾在某处调用Api.instance。但似乎您没有使用Api类的共享实例,但是您正在初始化private init()方法中的所有内容。

class Api {
    private var config: URLSessionConfiguration?
    private var session: SessionManager?

    static let shared = Api()

    private init() {
        config = URLSession.shared.configuration
        var headers = SessionManager.defaultHTTPHeaders
        headers.removeValue(forKey: "User-Agent")
        headers["User-Agent"] = APP_VERSION
        config?.httpAdditionalHeaders = headers
        session = SessionManager(configuration: Api.config!)
    }

    func requestFunction(_ path: String) {
        let req = session!.request("\(apiUrl())\(path)", method: .get, parameters: request.toJSON()).response(completionHandler: completionHandler)
    }
}

测试应该是

func test() {
    ...

    Api.shard.requestFunction(path, { (_, _) in
        semaphore.signal()
    })

    ...
}