Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCTestCase: UIApplication.shared.keyWindow returns nil

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()
like image 710
jahoven Avatar asked Jan 25 '17 19:01

jahoven


1 Answers

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.

like image 63
InsertWittyName Avatar answered Nov 01 '22 08:11

InsertWittyName