Waiting for Alamofire in Unit Tests

点点圈 提交于 2019-11-29 07:50:44

Use XCTestExpectation to wait for asynchronous processes, for example:

func testExample() {
    let e = expectation(description: "Alamofire")

    Alamofire.request(urlString)
        .response { response in
            XCTAssertNil(response.error, "Whoops, error \(response.error!.localizedDescription)")

            XCTAssertNotNil(response, "No response")
            XCTAssertEqual(response.response?.statusCode ?? 0, 200, "Status code not 200")

            e.fulfill()
    }

    waitForExpectations(timeout: 5.0, handler: nil)
}

In your case, if you're going to test your asynchronous method, you have to provide a completion handler to refreshThingy:

class Thingy {

    var property: String!

    func refreshThingy(completionHandler: ((String?) -> Void)?) {
        Alamofire.request(someURL)
            .responseJSON { response in
                if let json = response.result.value as? [String: String] {
                    completionHandler?(json["JSON"])
                } else {
                    completionHandler?(nil)
                }
        }
    }
}

Then you can test Thingy:

func testThingy() {
    let e = expectation(description: "Thingy")

    let thingy = Thingy()
    thingy.refreshThingy { string in
        XCTAssertNotNil(string, "Expected non-nil string")
        e.fulfill()
    }

    waitForExpectations(timeout: 5.0, handler: nil)
}

Frankly, this pattern of using a completion handler is probably something that you want in your refreshThingy, anyway, but I made it optional in case you might not want to supply a completion handler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!