我正在尝试编写一种方法,其中数据对象(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中使用的模式,但是如果你可能不想提供一个完成处理程序,我会把它作为可选项.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。