简体   繁体   中英

XCTestCase error when instantiate view controller from storyboard

I am quite new in using unit test in swift, and when i try to create unit test for measuring performance, i run into an error.

here is the code for my test case.

func testPerformaceFetchSearchResult(){
    //let ICD9ViewController = ICD9Controller() //this is not working since i need the IBOutlet also
    var ICD9ViewController:ICD9Controller!

    let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle:NSBundle(forClass: self.dynamicType))
    ICD9ViewController = storyboard.instantiateViewControllerWithIdentifier("ICD9Controller") as! ICD9Controller
    ICD9ViewController.beginAppearanceTransition(true, animated: false)

    ICD9ViewController.code = "0"
    ICD9ViewController.name = ""
    ICD9ViewController.desc = ""
    ICD9ViewController.sortBy = 1
    ICD9ViewController.customPage.pageNo = 1
    ICD9ViewController.customPage.pageSize = 10

    self.measureBlock(){
        ICD9ViewController.fetchSearchResult()
    }
}

The error is in this line

ICD9ViewController = storyboard.instantiateViewControllerWithIdentifier("ICD9Controller") as! ICD9Controller

And the error message is

Could not cast value of type ' appName .ICD9Controller' ( address ) to ' appName .ICD9Controller' ( differentAddress )

I have read several question about XCTestCase and most of the error is could not cast value of type _appName_.viewController to _appNameTests_.viewController which is not the case for me since i have already check the target membership for my storyboard and my controller.

My question is, how do i instantiate view controller from storyboard for unit test correctly?

The view controller and storyboard should only be available on the application target and then you can use @testable to access it on your tests.

Check if this post helps you as well. Also, if this doesn't work, please try to use NSBundle.mainBundle() instead of the test bundle.

After struggling for two days, i finally found the root problem.

The problem is cast issue, there are two module with the same name which is appName in my case. This make xCode confused, which is why it cannot cast the view controller.

Since module name usually take product name as its source, i change the test product name and my problem finally solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM