I am currently writing test on a MyViewController class with the following code:
let viewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MyViewController")
XCTAssertNotNil(viewController.view)
XCTAssertNotNil(viewController as? MyViewController)
This test does not work, the second assert always fails. When I debug, I can see my viewController has the correct type, but it looks like the type casting is always failing.
(lldb) po viewController
MyProject.MyViewController: 0x7f900c835600
(lldb) po viewController as? MyViewController
nil
The code of MyViewController and the storyboard are correctly included inside the Test project. There is also Cocoapods included.
I tested on an empty project and the issue remains present.
Does anyone has the same issue? Am I missing something?
Edit. I change the code to this:
let viewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MyViewController") as? MyViewController
XCTAssertNotNil(viewController)
But the issue is still present.
I tried this (I used ViewController throughout):
let viewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController")
XCTAssertNotNil(viewController.view)
XCTAssertNotNil(viewController as? ViewController)
That test passed!
So I tried your second way of writing it:
let viewController = UIStoryboard(
name: "Main", bundle: Bundle.main).instantiateViewController(
withIdentifier: "ViewController") as? ViewController
XCTAssertNotNil(viewController)
It passes on my machine!
If it's not passing for you, it might be because:
you failed to do a @testable import of your main module, or
you have an ambiguous class and you needed to say as? MyProject.MyViewController, or
the view controller with that identifier was not found, or
the view controller with that identifier is not a MyViewController
But, regardless, the test is telling you the truth and you need to think about that truth. You have not given us enough information to know which of those is your mistake.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With