迅速 – 在单元测试中等待Alamofire

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

概述我正在尝试编写一种方法,其中数据对象(Realm)使用Alamofire刷新它的属性.但我无法弄清楚如何对它进行单元测试. import Alamofireimport RealmSwiftimport SwiftyJSONclass Thingy: Object { // some properties dynamic var property // refr @H_404_2@ 我正在尝试编写一种方法,其中数据对象(Realm)使用Alamofire刷新它的属性.但我无法弄清楚如何对它进行单元测试.

import Alamofireimport RealmSwiftimport SwiftyJsONclass Thingy: Object {    // some propertIEs    dynamic var property    // refresh instance    func refreshThingy() {    Alamofire.request(.GET,URL)        .responseJsON {            response in                self.property = response["JsON"].string        }    }}

在我的单元测试中,我想测试Thingy是否可以正常刷新服务器.

import Alamofireimport SwiftyJsONimport XCTest@testable import MyModuleclass Thingy_Tests: XCTestCase {func testRefreshThingy() {    let testThingy: Thingy = Thingy.init()    testThingy.refreshProject()    XCTAssertEqual(testThingy.property,expected property)}

如何为此正确设置单元测试?

解决方法 使用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 code 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中使用的模式,但是如果你可能不想提供一个完成处理程序,我会把它作为可选项.

@H_404_2@ 总结

以上是内存溢出为你收集整理的迅速 – 在单元测试中等待Alamofire全部内容,希望文章能够帮你解决迅速 – 在单元测试中等待Alamofire所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

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

原文地址: https://outofmemory.cn/web/1001600.html

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

发表评论

登录后才能评论

评论列表(0条)

保存