在无效的 indexPath 处捕获了对 rect 的 NSInternalInconsistencyException 请求

Caught NSInternalInconsistencyException request for rect at invalid indexPath

以下行使程序崩溃:

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as! ItemCell

控制台日志显示以下错误:

"caught "NSInternalInconsistencyException", "request for rect at invalid index path (<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0})"

这是我检查过的要点列表:

完整代码如下:

import XCTest
@testable import ToDo

class ItemCellTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testSUT_HasNameLabel(){

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewControllerWithIdentifier("ItemListViewController") as! ItemListViewController

        _=controller.view

        let tableView = controller.tableView
        tableView.dataSource = FakeDataSource()

        let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as! ItemCell


        XCTAssertNotNil(cell.titleLabel)
    }
}


extension ItemCellTests{
    class FakeDataSource: NSObject, UITableViewDataSource {
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 1
        }

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            return UITableViewCell()
        }
    }
}

这里是 ItemCell.swift 代码:

import UIKit

class ItemCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!


    func configCellWithItem(item: ToDoItem){

    }
}

连接到故事板的所有属性都已连接。什么被忽视了?

目前我找到的解决方案是更改初始问题子函数,即:

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as! ItemCell

通过更改为以下内容以通过测试:

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell") as! ItemCell

看起来这段代码来自我的书。这是书中的一个已知错误。将测试方法更改为以下内容:

func testSUT_HasNameLabel(){

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewControllerWithIdentifier("ItemListViewController") as! ItemListViewController

    _=controller.view

    let tableView = controller.tableView
    let dataProvider = FakeDataSource()
    tableView.dataSource = dataProvider

    let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as! ItemCell

    XCTAssertNotNil(cell.titleLabel)
}

然后,当您稍后重构该代码以将设置放入 setUp 方法时,将 属性 let dataProvider = FakeDataSource() 添加到测试用例并将其设置为数据源table 视图 (tableView.dataSource = dataProvider) 在 setUp.