TableView单元测试异步服务调用

时间:2017-06-30 18:23:00

标签: ios objective-c swift

我正在为我的应用程序编写单元测试用例,其中UITableView包含来自服务器的数据。我为我的TableView添加了除numberOfRowsInSection之外的测试用例。

我正在关注UITableView测试用例的以下链接: Xcode 5 test UITableview with XCTest Framework

有人可以建议如何编写numberOfRowsInSection的测试用例来显示来自异步服务调用的数据吗? 任何想法或例子都会非常有用。

1 个答案:

答案 0 :(得分:1)

您可以使用OHHTTPStubs并使用json伪造您的数据。将带有面部数据的json文件添加到项目中(小心选择正确的目标)。然后使用下一个代码来测试数据:

import XCTest
import OHHTTPStubs

class TestSomeRequest: XCTestCase {

    // MARK: - Attributes
    fileprivate let endpoint = "yourendpoint"
    fileprivate let apiUrl = "yoururl"
    fileprivate let path = "yourpath"
}


// MARK: - Setup & Tear Down
extension TestSomeRequest {
    override func setUp() {
        super.setUp()
        stub(condition: isHost((URL(string: apiUrl)?.host)!) && isPath(path), response: {_ in
            guard let path = OHPathForFile("TestDataJson.json", type(of: self)) else {
                preconditionFailure("Could Not Find Test File!")
            }
            return OHHTTPStubsResponse(fileAtPath: path, statusCode: 200, headers: ["Content-Type": "application/json"])
        })
    }

    override func tearDown() {
        super.tearDown()
        OHHTTPStubs.removeAllStubs()
    }
}


// MARK: - Tests
extension TestSomeRequest {
    func testNumberOfRowsInSection() {
        let fetchExpectation = expectation(description: "Test Fetching")
        let viewController = YourViewController()
        YourDataManager.shared.fetchData(for: endpoint, success: {
            XCTAssertEqual(viewController.tableView.numberOfRows(inSection: 0), expectedNumberOfRows, "Number Of Rows In Section 0 Should Match!")
            fetchExpectation.fulfill()
        }, failure: nil)
        waitForExpectations(timeout: 60, handler: nil)
    }
}

如果您不想伪造数据,请使用此测试方法:

func testNumberOfRowsInSection() {
    let fetchExpectation = expectation(description: "Test Fetching")
    let viewController = YourViewController()
    YourDataManager.shared.fetchData(for: endpoint, success: {
        XCTAssertEqual(viewController.tableView.numberOfRows(inSection: 0), expectedNumberOfRows, "Number Of Rows In Section 0 Should Match!")
        fetchExpectation.fulfill()
    }, failure: nil)
    waitForExpectations(timeout: 60, handler: nil)
}