Testing for presentedViewController with GHUnit

207 Views Asked by At

After tapping a button, a UIImagePickerController gets displayed as a modal view controller with the following code:

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
[self presentViewController:imagePicker animated:YES completion:nil];

It works fine in the simulator and on the device, but I want to add a unit test for it (using GHUnit) and am trying to test that the presentedViewController is not nil.

However, when I run the test, I get the warning below printed to the console. Does anyone know how to get around this so I can test this properly?

Warning: Attempt to present <UIImagePickerController: 0xab5e990> on <UINavigationController: 0xab5a790> whose view is not in the window hierarchy!

Btw - I've already set shouldRunOnMainThread to return YES for this particular test file.

1

There are 1 best solutions below

0
On

During unit tests, your ViewController is not presented on the Window, therefore it can't present other Coordinators. You need to create a UIWindow, for example in your setup method and present the UINavigationController on the window in your test.

final class YourTest: XCTestCase {

    private var window: UIWindow!

    override func setUp() {
        super.setUp()

        window = UIWindow()
    }

    override func tearDown() {
        window = nil
        super.tearDown()
    }

    func testSomething() {
        let controller = YourCustomController()
        window.rootViewController = controller
        window.makeKeyAndVisible()

        controller.callSomeMethod()
        ...
    }

    ...
}