首页 > 解决方案 > 在 xib 文件中对自定义 tableviewcell 进行单元测试

问题描述

我在情节提要中有一个带有 tableview 的视图控制器类。在另一个单独的 xib 文件中,我有一个自定义表格视图单元格,其中包含自定义表格视图单元格类中的图像视图、标签等属性。

现在我必须编写单元测试用例来测试这个自定义单元格及其属性。我尝试了以下方法,

import XCTest
@testable import Citizens_Bank

class InvestmentTableViewCellTests: XCTestCase {

    var newsVC: NewsViewController!

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

    }

   func testCustomViewContainsAView() {
    let bundle = Bundle(for: NewsDetailsTableViewCell.self)
    guard let _ = bundle.loadNibNamed("NewsDetailsTableViewCell", owner: nil)?.first as? UIView else {
        return XCTFail("CustomView nib did not contain a UIView")
     }
  }

  func testCustomCell() {
     let customCell: NewsDetailsTableViewCell = accountsVC.myTableView.dequeueReusableCell(withIdentifier: "newsDetailsCell") as! NewsDetailsTableViewCell
    XCTAssertNotNil(customCell, "No Custom Cell Available")
  }
}

testCustomcell 测试用例函数因控制台日志中的此错误而崩溃“致命错误:在展开可选值时意外发现 nil”。如何测试我的自定义表格视图单元格及其属性?提前致谢。

标签: swiftunit-testinguitableview

解决方案


首次使用:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let yourView = storyboard.instantiateViewController(withIdentifier: "yourView") as! yourView

然后打电话

 let customCell = yourView.myTableView.dequeueReusableCell(withIdentifier: "yourView") as! NewsDetailsTableViewCell

推荐阅读