单元测试从故事板中快速转换视图控制器不起作用

时间:2015-04-16 08:32:25

标签: ios iphone unit-testing swift

我写了下面的测试用例,它在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)。

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

3 个答案:

答案 0 :(得分:13)

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

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

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

答案 1 :(得分:12)

几分钟前我遇到了同样的问题。这是我如何解决它。

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

    希望这有帮助!

答案 2 :(得分:0)

  

尝试一下行之有效

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")
}
}