使用XCTest测试视图标题

时间:2013-12-10 03:27:38

标签: ios xctest

我正在使用XCtest来测试视图的标题。试着养成先写测试的习惯。设置看起来像

- (void)setUp
{
    [super setUp];
    self.appDelegate = [[UIApplication sharedApplication] delegate];
    self.tipViewController = self.appDelegate.tipViewController;
    self.tipView = self.tipViewController.view;

    self.settingsViewController = self.appDelegate.settingsViewController;
    self.settingsView = self.settingsViewController.view;
}

问题是“settingsViewController”。我有两个功能用于实际测试:

- (void) testTitleOfMainView{
    XCTAssertTrue([self.tipViewController.title isEqualToString:@"Tip Calculator"], @"The title should be Tip Calculator");
    //why does this not work?
    //    XCTAssertEqual(self.tipViewController.title, @"Tip Calculator", @"The title should be Tip Calculator");
}

- (void) testTitleOfSettingsView{
    //make the setttings view visible
    [self.tipViewController onSettingsButton];

    //test the title
    XCTAssertTrue([self.settingsViewController.title  isEqualToString:@"Settings"], @"The title should be Settings");
}

“testTitleOfMainView”有效。但是“testTitleOfSettingsView失败,因为self.settingsViewController是nil。我可以理解为什么。视图还没有被初始化。所以我尝试将消息发送到主控制器,它将settignscontroller视为

[self.tipViewController onSettingsButton];

settingsController仍为零。我应该使用嘲笑吗?有人建议我提出另一个问题 xctest - how to test if a new view loads on a button press

我应该将设置视图子类化并手动启动吗?谢谢。

1 个答案:

答案 0 :(得分:8)

远离在实际导航堆栈中实际加载视图。真正的UI交互通常需要运行循环来接收事件,因此它们不能在快速单元测试中工作。所以扔掉你的setUp代码。

相反,单独实例化视图控制器,并加载它:

- (void)testTitleOfSettingsView
{
    SettingsViewController *sut = [[SettingsViewController alloc] init];

    [sut view];    // Accessing the view causes it to load

    XCTAssertEquals(@"Settings", sut.title);
}

另外,了解XCTest中可用的各种断言,而不仅仅是XCAssertTrue。避免在这些断言中发表评论;小测试中的单个断言应该说明一切。