在单元测试中运行异步代码的问题

时间:2019-07-01 14:01:11

标签: swift unit-testing asynchronous

所以我在应用程序的单元测试中运行异步代码时遇到问题。我正在使用期望值,以便在测试完成之前等待代码执行。异步代码通过heroku运行以获取值,然后应在应用程序中返回它们。通过此单元测试,我试图确保通过heroku的连接正常工作。这是我的代码:

func test() {
    let url = "https://s.herokuapp.com/test"

    let params: [String: Any] = ["account_id": AppState.sharedInstance.user.accounttoken]

    let expectation = self.expectation(description: "Testing returning value")

    let totalBalance = ""
    Alamofire.request(url, method: .post, parameters: params)
        .validate(statusCode: 200..<300)
        .responseJSON { response in
            switch response.result {
            case .success:
                print("Returned with success")
            case .failure(let error):
                let status = response.response?.statusCode
                print("Failed, status: \(status)")
                print("Here is the error: \(error)")
            }

            if let result = response.result.value {
                let balance = result as! NSDictionary
                let totalBalance = String(describing: "\(balance["Balance"]!)")
            }
            XCTAssert(totalBalance != "")
            expectation.fulfill()
    }
    waitForExpectations(timeout: 10, handler: nil)
    XCTAssert(totalBalance != "")
}

我感到困惑的原因是因为我没有错误让异步代码返回实际应用中的值。我在单元测试中只有等待时间的问题。我遇到了两个失败错误,一个是针对XCTAssert的错误,另一个是对于waitForExpectations超过10秒的错误。如果可以帮助您找到解决方法,以下一些错误也会弹出:

Error Messages

以下是文本形式的错误消息:

  

2019-07-01 09:44:38.181971-0400 Spotbirdparking [49677:4306598] TIC TCP   Conn失败[6:0x6000030b7cc0]:3:-9816 Err(-9816)2019-07-01   09:44:38.188607-0400 Spotbirdparking [49677:4306598]   NSURLSession / NSURLConnection HTTP加载失败   (kCFStreamErrorDomainSSL,-9816)2019-07-01 09:44:38.188819-0400   Spotbirdparking [49677:4306598]任务   。<1> HTTP加载失败(错误   代码:-1200 [3:-9816])2019-07-01 09:44:38.189215-0400   Spotbirdparking [49677:4306623]任务   。<1>完成,错误-代码:   -1200 /Users/drewloughran/Desktop/SpotBird/SpotbirdparkingTests/SpotbirdparkingTests.swift:117:   错误:-[SpotbirdparkingTests.SpotbirdparkingTests test_stripe]:   异步等待失败:超过10秒的超时时间,   未实现的期望:“测试条带的返回值”。

我也是新手,所以对此问题的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

提请,请首先检查此错误。您的请求无法加载。

 HTTP load failed (error code: -1200 [3:-9816]) 2019-07-01 09:44:38.189215-0400 Spotbirdparking[49677:4306623] Task .<1> finished with error - code: -1200 

还要确保正在执行用于满足期望的代码块。可能不是,这就是您的期望未达到且测试失败的原因。

此外,from this documentation我可以看到您的验证与自动验证案例相交。这是多余的。

 Response Validation
By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.

Manual Validation
Alamofire.request("https://httpbin.org/get")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .response { response in
        switch response.result {
        case .success:
            print("Validation Successful")
        case .failure(let error):
            print(error)
        }
    }
Automatic Validation
Automatically validates status code within 200...299 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.

Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
    switch response.result {
    case .success:
        print("Validation Successful")
    case .failure(let error):
        print(error)
    }
}

祝你好运!

答案 1 :(得分:0)

您不应通过实际的网络测试Alamofire通话。这会导致您每次测试时都访问网络。它是不可靠的(网络可能会发生故障)并且是不必要的。我们知道网络在做什么!您也不必测试Alamofire。它不是您要测试的,而且您再次知道它的作用。因此,您应该重构代码以进行测试并模拟网络调用。

相关问题