When I call
UIApplication.shared.keyWindow
to try and set the root view controller in my test class, the key window returns nil. Why is this happening?
Here's how I set up my storyboard:
let testBoard = UIStoryboard(name: "TestStoryboard", bundle: Bundle(for: type(of: self)))
let vc = testBoard.instantiateViewController(withIdentifier: "TestController")
UIApplication.shared.keyWindow?.rootViewController = vc
_ = vc.view
vc.viewDidLoad()
Create a window and assign the view controller.
let testBoard = UIStoryboard(name: "TestStoryboard", bundle: Bundle(for: type(of: self)))
let vc = testBoard.instantiateViewController(withIdentifier: "TestController")
let window = UIWindow()
window.rootViewController = vc
window.makeKeyAndVisible()
vc.view.layoutIfNeeded()
// Add test here
I notice after that you're also calling vc.view
and viewDidLoad
. I'd recommend just accessing the view to get it to load and not calling viewDidLoad
implicitely - personally I use vc.view.layoutIfNeeded()
Depending on what you actually need to test, for me it's very rare to have to assign the view controller to the window itself. You can normally get away with just creating an instance of the view controller, and if you're testing any of the UI code also ensuring the view is populated.
One of the only times I've needed to assign the view controller to a window is when testing things like navigation, where I want to assert that another view controller is being presented modally due to some action.
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