Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automated testing of segues

I want to create an integration test which shows that a certain action results in the display of a modal view controller. The storyboard is setup with 2 viewcontrollers, one with a custom ViewController class the second with a default UIViewController class and title "second". The segue is set-up to be modal with identifier "modalsegue". Running the app in the simulator works brilliantly, but I am having a lot of trouble defining a correct test.

ViewController.m:

@implementation ViewController

- (IBAction)handleActionByPerformingModalSegue {
    [self performSegueWithIdentifier:@"modalsegue" sender:self];
}
@end

Test:

- (void)testActionCausesDisplayOfSecondViewController {
    ViewController * vc =
      [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]   
          instantiateViewControllerWithIdentifier:@"ViewController"];

    [vc handleActionByPerformingModalSegue];
    STAssertEquals(vc.presentedViewController.title, @"second",
        @"Title of presented view controller should be second but is %@",   
        vc.presentedViewController.title, nil);
}

Running the test results in the following output:

2013-06-23 17:38:44.164 SeguesRUs[15291:c07] Warning: Attempt to present <UIViewController: 0x7561370> on <ViewController: 0x7566590> whose view is not in the window hierarchy!
SeguesRUsTests.m:33: error: -[SeguesRUsTests testActionCausesDisplayOfSecondViewController] : '<00000000>' should be equal to '<9c210d07>': Title of presented view controller should be second but is (null)

What am I doing wrong? Is there an easy way to avoid the first message?

like image 724
Matthijs P Avatar asked Nov 13 '22 02:11

Matthijs P


1 Answers

As the error message points out, the problem is that you're trying to present on a UIViewController whose view is not in the UIWindow hierarchy.

The easiest way to fix it:

- (void)testExample {

    //
    // Arrange
    // Storyboard
    //
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

    //
    // Arrange
    // View Controller
    //
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
    [UIApplication sharedApplication].keyWindow.rootViewController = viewController;

    //
    // Act
    //
    [viewController performSegueWithIdentifier:@"ModalSegue" sender:nil];

    //
    // Assert
    //
    XCTAssertEqualObjects(viewController.presentedViewController.title, @"Second");

}
like image 186
Rudolf Adamkovič Avatar answered Nov 15 '22 10:11

Rudolf Adamkovič