单元测试在cellForRowAtIndexPath崩溃

时间:2017-12-15 16:27:58

标签: ios swift uitableview unit-testing

我有一些带有一些行的简单tableview。每行都是带有xib文件的自定义单元格。我已经实现了委托和数据源,并且在我运行应用程序时工作正常。这就是我实施它的方式。

class P: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        registerCell()
    }

    func registerCell() {
        self.tableView.register(UINib(nibName: "PCell", bundle: nil), forCellReuseIdentifier: "cell")
    }

    #number of rows implemented here

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PCell
        cell.titleLabel.text = "Great"
        return cell
    }
}

此代码工作正常。

问题是,当我尝试对tableView进行单元测试时,我遇到了问题。这就是我单元测试的方式

class MockPController: PController {

}

class PControllerTests: XCTestCase {
    let mpc = MockPController()

    //THIS IS WORKING
    func testNumberOfSections() {
        mpc.viewDidLoad()
        XCTAssertEqual(mpc.numberOfSections(in: mpc.tableView), 5)
    }

    func testTitleForPCells() {
        mpc.viewDidLoad()
        var cell = mpc.tableView(mpc.tableView, cellForRowAt: IndexPath(row: 0, section: 1)) as! PCell
        //THE APP CRASHES AT THE CELLFORROWATINDEXPATH FUNCTION IN ACTUAL CODE - HERE "let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PCell"
        //APP CRASHES HERE SAYING "Could not cast value of type 'Project.PCell' to 'ProjectTests.PCell'
    }
}

在获得此应用程序崩溃时,我在MockPController中为registerCell()添加了一个覆盖函数,因此新的MockPController变为

class MockPController: PController {
    override func registerCell() {
        self.tableView.register(PCell.self, forCellReuseIdentifier: "cell")
    }
}

添加此覆盖功能后,我没有在dequeueReusableCell崩溃,但现在应用程序崩溃说出口变量titleLabel为零。

因为覆盖registerCell()函数,所以我猜它没有得到正确的单元格实例。但是没有它也会崩溃。

我做错了什么?

我搜索了谷歌,但我没有得到任何结果。

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试测试UITableView的{​​{1}}方法。这不是你想要的。您想测试cellForRowAt:课程。 为此,请使用超类init PCell实现PCell。然后像init(style:reuseIdentifier:)一样调用你自己的方法,并断言你单元格的标题是你所期望的。

编辑:

pcell.doSomethingThatSetTheTitle()
相关问题