This can also be done as follows:
Let's say we have a button that, when clicked, shows the view controller:
- (void) didTapButton { UIAlertController* c = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert]; [self presentViewController:c animated:ANIMATED completion:nil]; }
Note that the ANIMATED parameter is not "YES" or "NO". In PrefixHeader it is defined as:
#define ANIMATED (getenv("runningTests") == NULL)
and runTests is the environment variable defined in the test task. We do not want animation when running unit / integration tests.
The testing method looks like this:
- (void) testButtonWillShowAlertView { UIApplication.sharedApplication.delegate.window.rootViewController = controller; [controller.button sendActionsForControlEvents:UIControlEventTouchUpInside]; XCTAssertEqualObjects(controller.presentedViewController.class, UIAlertController.class); }
Important line
UIApplication.sharedApplication.delegate.window.rootViewController = controller;
Obviously, the rootViewController on the UIWindow must be installed.
source share