代码之家  ›  专栏  ›  技术社区  ›  user579911

在xib文件中对自定义tableviewcell进行单元测试

  •  0
  • user579911  · 技术社区  · 6 年前

    我有一个视图控制器类,在故事板中有一个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测试用例函数在控制台日志“fatal error:unwrapping an optional value”中由于此错误而崩溃。如何测试自定义TableView单元格及其属性?提前谢谢。

    1 回复  |  直到 6 年前
        1
  •  0
  •   A.Munzer    6 年前

    首次使用:

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

    然后打电话

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