如何使用XCTest测试navigationBar是否在Objective-C中未设置为特定颜色?
尝试测试表视图控制器的navigationBar颜色。我已经在表视图控制器中设置了navigationController的barTintColor。
Trying to test for navigationBar colour of a table view controller. I've set the barTintColor of the navigationController in the table view controller.
我编写了以下测试:
- (void)testNavBarColourOfMasterViewController
{
VAGMasterViewController *mvc = [[VAGMasterViewController alloc] init];
[mvc view];
XCTAssertEqualObjects([[[mvc navigationController] navigationBar] barTintColor], [UIColor whiteColor]);
}
错误:
test failure: -[VAGMasterViewControllerTests testNavBarColourOfMasterViewController] failed: (([[[mvc navigationController] navigationBar] barTintColor]) equal to ([UIColor whiteColor])) failed: ("(null)") is not equal to ("UIDeviceWhiteColorSpace 1 1")
显然我尝试读取barTintColor的颜色,该颜色为null。
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?
亲切的问候。
仅创建视图控制器将导致导航控制器(因此,条形)为 nil
。解决方案是创建一个导航控制器:
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]);
}
也不是访问导航控制器或其属性的好习惯(在这种情况下,请在 viewDidLoad
中添加bar),因为可能会在导航控制器将自身与视图控制器链接之前触发视图加载,从而导致问题。
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.