在单元测试中等待Alamofire

在单元测试中等待Alamofire,第1张

在单元测试等待Alamofire

使用

XCTestExpectation
等待异步过程,例如:

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 pre not 200") e.fulfill()    }    waitForExpectations(timeout: 5.0, handler: nil)}

对于您的情况,如果要测试异步方法,则必须提供一个完成处理程序

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

然后您可以测试

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

坦白说,

refreshThingy
无论如何,使用完成处理程序的这种方式可能都是您想要的,但是如果您不想提供完成处理程序,我将其设为可选。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4947235.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存