Can't cast custom UIViewController from UIStoryboard in XCTest Can't cast custom UIViewController from UIStoryboard in XCTest swift swift

Can't cast custom UIViewController from UIStoryboard in XCTest


I came up with a better solution than making everything public. You actually just need to use a storyboard that comes from the test bundle instead of using nil (forcing it to come from the main target's bundle).

var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))vc = storyboard.instantiateViewControllerWithIdentifier("LoginVC") as LoginViewControllervc.loadView()


Thanks @Derrik Hathaway for the key to the solution. The application and the test target are different modules.

My application has the unfortunate name of TestingViewControllers To correct the issue I made the following changes and made the ViewController a public class back in the Application code.

Added this line to test Case:

import TestingViewControllers

Change the test case to this:

func testExample() {  var storyBoard: UIStoryboard?  var anyVC: AnyObject?  var viewController: TestingViewControllers.ViewController?  storyBoard = UIStoryboard(name:"Main", bundle: nil)  XCTAssert(storyBoard != nil, "Test Not Configured Properly")  anyVC = storyBoard?.instantiateInitialViewController()  viewController = anyVC as? TestingViewControllers.ViewController  XCTAssert(viewController != nil, "Test Not Configured Properly")  // This is an example of a functional test case.  XCTAssert(true, "Pass")}

Test case passes


Have you set the storyboardID if you have then you can cast it like this.

You need also rename your view controller class to for example here MyAppViewController make main storyboard use it instead of the standard viewcontroller class then set the storyboardID to for example MyappVC

  var sut : MyAppViewController!override func setUp() {    super.setUp()    // get a reference to storyboard and the correct    // viewcontroller inside it. Remember to add    // storyboardID in this case "MyappVC"    let StoryBoard = UIStoryboard.init(name: "Main", bundle: nil)    sut = StoryBoard.instantiateViewControllerWithIdentifier("Myapp VC")as!    CalculatorViewController    //trigger viewDidLoad()    _ = sut.view