gpt4 book ai didi

ios - 在 XCode 单元测试中测试导航

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:01:14 26 4
gpt4 key购买 nike

我正在尝试在单元测试中测试 UIViewControllers 导航,我能够进行后端测试,但要增加测试 UIViewControllers 的测试覆盖率,

遇到一个奇怪的问题,所以我有一个 ViewController(在没有 Storyboard的情况下手动创建),它有两个按钮,单击这些按钮中的每一个都会带您进入另一个 View (将新 View 推送到导航 Controller 上)。

viewDidLoad中初始化如下

// Setup the action of button
[self.button1 addTarget:self
action:@selector(goToView1)
forControlEvents:UIControlEventTouchUpInside];

[self.button2 addTarget:self
action:@selector(goToView2)
forControlEvents:UIControlEventTouchUpInside];

这是我推送这两个 View 的代码

- (void)goToView1 
{
// Go to the FAQ Screen
ViewController1 *viewController = [[ViewController1 alloc] init];
[self.navigationController pushViewController:viewController
animated:YES];
}
- (void)goToView2
{
// Go to the checkin screen
ViewController2 *viewController =[[ViewController2 alloc] init];
[self.navigationController pushViewController:viewController
animated:YES];
}

在我的测试类中,我试图像这样测试它

- (void)testNavigation 
{
//Initialize the view controller and call the navigation functions
[self.testController goToView1];

XCTAssertTrue([self.navigationController.topViewController
isKindOfClass:[ViewController1 class]],
@"Did not navigate Controller 1");

[self.navigationController popToViewController:self.testController
animated:NO];

[self.testController goToView2];

XCTAssertTrue([self.navigationController.topViewController
isKindOfClass:[ViewController2 class]],
@"Did not navigate to Controller 2");

}

所以这个测试实际上失败了,我猜的原因是因为我在用动画调用 PushViewcontroller 后立即检查 ViewController:是,如果我在没有动画测试通过的情况下推送 View Controller (因为 View 被立即推送并且断言检查正常)。

所以我的问题是,无论如何我可以在某个地方放一个钩子(Hook)来检查 View 是否在检查断言之前被推送(我不想仅仅为了通过测试而关闭动画,因为它会杀死整个目的)我也不想任意延迟。在运行测试逻辑之前,我能否以某种方式检查推送动画是否已完成以及 View 是否最终位于顶部?

最佳答案

M David 部分正确:您应该使用 XCTestExpectation(与 Xcode 6 及更高版本一起使用)包装 'dispatch_after',如下所示:

XCTestExpectation *completionExpectation = [self expectationWithDescription:@"WaitingForWhatever"];
double delayInSeconds = 3.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, popTime * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
XCTAssertTrue([TestClass.navigationController.topViewController isKindOfClass:[requiredClass class]],@"View Controller not pushed properly");
[completionExpectation fulfill];
});
[self waitForExpectationsWithTimeout: delayInSeconds+2 handler:nil];

关于ios - 在 XCode 单元测试中测试导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com