2014-10-29 82 views
3

我想知道是否有方法在使用自動佈局時在單元測試中測試iOS視圖的佈局。現在我試着簡單地初始化視圖控制器,然後檢查視圖的框架。但是,每個視圖上的幀仍然是原點=(x = 0,y = 0)size =(width = 0,height = 0)。使用XCTest測試自動佈局

- (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)); 
} 

我已經嘗試添加

[_viewController.view needsUpdateConstraints]; 

[_viewController.view updateConstraints]; 

[_viewController updateViewConstraints]; 

[_viewController viewWillAppear:YES]; 

但他們都沒有幫助。

使用XCTest時,是否有可能使自動佈局運行?

+0

您是否嘗試過'setNeedsLayout'後跟'layoutIfNeeded'?你可以讓佈局在測試中運行,我在這裏執行:https://github.com/jrturton/UIView-Autolayout/blob/master/Example/AutoLayoutTests/AutoLayoutConstraintsSpec.m但沒有視圖控制器,只是觀點。 – jrturton 2014-10-29 15:44:29

+0

完美的工作。謝謝。 – Rubberduck 2014-10-30 09:38:06

+0

好吧,我會將其添加爲答案 – jrturton 2014-10-30 12:09:50

回答

4

你試過setNeedsLayout後跟layoutIfNeeded

你絕對可以得到佈局在測試中運行,我這樣做here,但沒有視圖控制器,只是視圖。