ios - 异步服务调用的 TableView 单元测试

标签 ios objective-c swift

我正在为我的应用程序编写单元测试用例,该应用程序具有 UITableView 以及来自服务器的数据。除了 numberOfRowsInSection 之外,我已经为我的 TableView 添加了测试用例。

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

谁能建议如何为 numberOfRowsInSection 编写一个测试用例来显示来自异步服务调用的数据? 任何想法或示例都会非常有帮助。

最佳答案

您可以使用 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)
}

关于ios - 异步服务调用的 TableView 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44852739/

相关文章:

iOS 和 Twitter 集成 - 获取多个用户的状态

ios - 以下状态有什么区别?

objective-c - 在右栏按钮项的选择器中传递参数

ios - 如何使用面向协议(protocol)的编程来改进我的 Swift 代码?

ios - 如何在适用于各种 View Controller 的快速文件模型中创建警报

ios - 使用 Apple 服务器验证消耗性 IAP 的正确方法是什么?

javascript - 如何询问用户是否希望在 CloudKit JS 中被发现?

ios - 如何仅从 UIDatePickerMode.DateAndTime 中删除分钟

ios - 如何修复弃用警告消息?

ios - Swift TableView 人口