gpt4 book ai didi

swift - 在单元测试中等待 Alamofire

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:56 25 4
gpt4 key购买 nike

我正在尝试编写一种方法,其中数据对象 (Realm) 使用 Alamofire 刷新其属性。但我不知道如何对其进行单元测试。

import Alamofire
import RealmSwift
import SwiftyJSON

class 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 Alamofire
import SwiftyJSON
import XCTest
@testable import MyModule

class 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 中想要的东西,无论如何,但我将其设为可选,以防您可能不想提供完成处理程序。

关于swift - 在单元测试中等待 Alamofire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34278072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com