Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test Swift- casting view controller from storyboard not working

I have written the below test case which worked fine in swift 1.1. But in 1.2 its breaking.

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

Error while running the unit test

Could not cast value of type 'testProject.AboutViewController' (0x105b0ad30) to 'testProjectTests.AboutViewController' (0x116e51d20).

I have done enough research to resolve this issue. But couldn't able to do it. I hope some of you come across this problem and will able to help me here.

like image 259
vinothp Avatar asked Apr 16 '15 08:04

vinothp


3 Answers

I faced the same problem a few minutes ago. Here's how i solved it.

  1. Add storyboard to the testing target
  2. Load the view controller this way:
var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle:NSBundle(forClass: self.dynamicType))

self.vc = storyboard.instantiateViewControllerWithIdentifier("gettingStartedView") as! MainViewController

self.vc.loadView()

Hope this helps!

like image 62
Astha Trivedi Avatar answered Nov 18 '22 21:11

Astha Trivedi


Try this it worked

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")
}
}
like image 36
Devesh Avatar answered Nov 18 '22 19:11

Devesh


I had the same problem and solution is:

  • Add storyboard Main and AboutViewController in test target
  • Replace UIStoryboard(name: "Main", bundle:NSBundle.mainBundle()) with UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.classForCoder))

This way you'll load storyboard and initialize controller from test target bundle, instead from using it from main target bundle. Check this link for details

like image 13
Igor Avatar answered Nov 18 '22 21:11

Igor