通常我试着查询逻辑分成几个部分:它采用了路由器3)映射模型
而这一切的部分你可以测试
1)路由器2)API客户端。
如何测试API客户端:
fileprivate func testPerformanceOfGetNewsFromAPI() {
let expectationTimeout: Double = 30.0
self.measure {
let expectation = self.expectation(description: "Get gifters")
NewsAPIClient.getNews(closure: { response in
expectation.fulfill()
})
self.waitForExpectations(timeout: expectationTimeout) { error in
XCTAssertNil(error)
}
}
}
此测试将检查。 APIClient可以在30秒内收到答复。
如何测试映射:
对于测绘,我用JASON:https://github.com/delba/JASON
设置你的快捷文件:
import XCTest
import JASON
@testable import ProjectName
final class NewsTests: XCTestCase {
// MARK: - Properties
fileprivate var news: News!
// MARK: - Lyfecycles
override func setUp() {
super.setUp()
news = mockExample()
}
override func tearDown() {
news = nil
super.tearDown()
}
}
然后,在此创建班级你的模拟:
fileprivate func mockExample() -> ExampleModel? {
let data: Data
let json: JSON
do {
try data = Data(resource: "MyExampleFile.json") // Here enter your JSON example file. Target member ship for this file should be your test target
try json = JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as! JSON
} catch let error {
XCTFail(error.localizedDescription)
return nil
}
let model = ExampleModel(json: json)
return model
}
然后,可以在这个类写测试:
fileprivate func testMapping() {
XCTAssertNotNil(news)
XCTAssertEqual(news.title, mockExample()?.title)
XCTAssertEqual(news.text, mockExample()?.text)
XCTAssertEqual(news.timeStamp, mockExample()?.timeStamp)
}
在测试逻辑,也可以添加图像上载(如果它们存在于JSON)。因此,您可以检查当前模型是否适合您,可以处理JSON响应。
感谢您的好解答。但我认为这不完全是我要求的。我也将请求流分离为逻辑部分。如果某些部分失败(例如,错误的HTTP代码,无法解析的无效响应,例如),则需要测试请求完成者是否会被终止。如果流程不停止,如果有错误,那么我可以得到运行时错误。谢谢。 – Yura