How do I use XCTest to test if a navigationBar is

2019-09-09 15:59发布

Trying to test for navigationBar colour of a table view controller. I've set the barTintColor of the navigationController in the table view controller.

I have written the following test:

- (void)testNavBarColourOfMasterViewController
{
    VAGMasterViewController *mvc = [[VAGMasterViewController alloc] init];
    [mvc view];
    XCTAssertEqualObjects([[[mvc navigationController] navigationBar] barTintColor], [UIColor whiteColor]);
}

Error:

test failure: -[VAGMasterViewControllerTests testNavBarColourOfMasterViewController] failed: (([[[mvc navigationController] navigationBar] barTintColor]) equal to ([UIColor whiteColor])) failed: ("(null)") is not equal to ("UIDeviceWhiteColorSpace 1 1")

Apparently when I try to read the colour of the barTintColor it is null. How can this be if it's set in viewDidLoad in the controller?

Kind regards.

1条回答
等我变得足够好
2楼-- · 2019-09-09 16:15

Creating just a view controller will lead to the navigation controller (and thus, the bar) being nil. The solution is to create a navigation controller:

- (void)testNavBarColourOfMasterViewController
{
    VAGMasterViewController *mvc = [[VAGMasterViewController alloc] init];
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:mvc];
    [mvc view];
    XCTAssertEqualObjects([[[mvc navigationController] navigationBar] barTintColor], [UIColor whiteColor]);
}

Also, it is not good practice to access the navigation controller or its properties (in this case, bar) in viewDidLoad, because the view loading may be triggered before the navigation controller has linked itself with the view controller, causing issues.

查看更多
登录 后发表回答