【问题标题】:Unit Test Swift- casting view controller from storyboard not working单元测试Swift-从情节提要中投射视图控制器不起作用
【发布时间】:2015-04-16 08:32:25
【问题描述】:

我编写了以下测试用例,它在 swift 1.1 中运行良好。但在 1.2 中它的破坏。

class AboutViewController_Tests: XCTestCase
{
//var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType)) // Used in swift 1.1

var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle:NSBundle.mainBundle()) // Replaced this in swift 1.2
var aboutViewController:AboutViewController!

override func setUp()
{
super.setUp()
aboutViewController = storyboard.instantiateViewControllerWithIdentifier("AboutViewController") as! AboutViewController
aboutViewController.viewDidLoad()
XCTAssertNotNil(aboutViewController, "About not nil")
}
}

运行单元测试时出错

无法将“testProject.AboutViewController”(0x105b0ad30)类型的值转换为“testProjectTests.AboutViewController”(0x116e51d20)。

我已经做了足够的研究来解决这个问题。但是做不到。我希望你们中的一些人遇到这个问题并能够在这里帮助我。

【问题讨论】:

    标签: ios iphone unit-testing swift


    【解决方案1】:

    我遇到了同样的问题,解决方法是:

    • 在测试目标中添加故事板MainAboutViewController
    • UIStoryboard(name: "Main", bundle:NSBundle.mainBundle()) 替换为 UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.classForCoder))

    这样您将从测试目标包中加载故事板并初始化控制器,而不是从主目标包中使用它。 Check this link for details

    【讨论】:

      【解决方案2】:

      几分钟前我遇到了同样的问题。这就是我解决它的方法。

      1. 将故事板添加到测试目标
      2. 以这种方式加载视图控制器:
      var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle:NSBundle(forClass: self.dynamicType))
      
      self.vc = storyboard.instantiateViewControllerWithIdentifier("gettingStartedView") as! MainViewController
      
      self.vc.loadView()
      

      希望这会有所帮助!

      【讨论】:

      • 此更改也为我修复了它
      【解决方案3】:

      试试这个效果很好

      class VehicleListControllerSpecs: XCTestCase {
      
      var listController: VehicleListController!
      
      override func setUp() {
          super.setUp()
          let storyboard = UIStoryboard(name: "Main", bundle: nil)
          let vc = storyboard.instantiateViewController(withIdentifier: "VehicleListController") as! VehicleListController
      listController = vc
          _ = listController.view
          // Put setup code here. This method is called before the invocation of each test method in the class.
      }
      
      func testListViewHasTableView() {
          XCTAssertNotNil(listController.tableView,"view doesnt has tableview")
      }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-03-28
        • 2018-05-18
        • 1970-01-01
        • 2015-06-02
        • 2023-04-08
        • 2013-10-21
        • 1970-01-01
        • 2017-07-08
        • 1970-01-01
        相关资源
        最近更新 更多