大佬教程收集整理的这篇文章主要介绍了迅速 – 在单元测试中等待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) }
如何为此正确设置单元测试?
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中使用的模式,但是如果你可能不想提供一个完成处理程序,我会把它作为可选项.
以上是大佬教程为你收集整理的迅速 – 在单元测试中等待Alamofire全部内容,希望文章能够帮你解决迅速 – 在单元测试中等待Alamofire所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。