0

I have defined my own class with methods that fits signature of URLSession complete callback, e. g. (Data?, Response?, Error?) -> Void. The method contains common logic for handling response, e. g. checking data, parsing it etc. Now I would like to unit test this method. The methods contains some verification, for instance,

guard let data = data else {
    //some logic
    return
}

Here I would like to test that function will really be terminated. Of course it is not possible to achieve it against void return (I think so, maybe I missed something). Another option - mark the method as throws, and then test for a specific errors. But then this method will not fit into URLSession.shared.dataTask method. Am I paranoid about these things? Is there any possibility to achieve it? Thanks in advance.

4

1 回答 1

1

通常我会尝试将查询逻辑分成几个部分:

1) 路由器 2) 使用路由器的 API 客户端 3) 映射模型

您可以测试所有这些部分。

如何测试 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

设置你的 swift 文件:

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 响应。

于 2017-04-07T19:28:02.517 回答