Search code examples
iosobjective-cautolayoutxctest

Testing autolayout with XCTest


I'm trying to figure out if there is a way to test the layout of an iOS view in unit tests when using autolayout. Right now I try to simply initialize the view controller, and then check the frames of the views. However, the frame on each view remains origin=(x=0, y=0) size=(width=0, height=0).

- (void)setUp {
    [super setUp];

    _viewController = [[AddPlayerViewController alloc] init];
    _viewController.view.frame = CGRectMake(0, 0, 320, 460);
    [_viewController view];
}

- (void)testViewsAreInsideWindow {
    [self checkIfViewIsInsideWindow:_viewController.txtfNewPlayer];
    [self checkIfViewIsInsideWindow:_viewController.btnNewPlayer];
    [self checkIfViewIsInsideWindow:_viewController.tblPlayers];
}

- (void)checkIfViewIsInsideWindow:(UIView *)view {
    CGRect windowFrame = _viewController.view.frame;
    CGRect viewFrame = view.frame;
    XCTAssertTrue(CGRectContainsRect(windowFrame, viewFrame));
}

I've tried adding

[_viewController.view needsUpdateConstraints];

or

[_viewController.view updateConstraints];

or

[_viewController updateViewConstraints];

or

[_viewController viewWillAppear:YES];

but none of them have helped.

Is it at all possible to get autolayout to run when using XCTest?


Solution

  • Have you tried setNeedsLayout followed by layoutIfNeeded?

    You can definitely get layout to run in tests, I do it here, but that doesn't have a view controller, just views.