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.