我正在写一个单元测试,我发现popViewControllerAnimated:YES不起作用。
(void)testNavi {
UINavigationController *navi = [[UINavigationController alloc] init];
UIViewController *controllerA = [[UIViewController alloc] initWithNibName:nil bundle:nil];
UIViewController *controllerB = [[UIViewController alloc] initWithNibName:nil bundle:nil];
[navi pushViewController:controllerA animated:NO];
[navi pushViewController:controllerB animated:NO];
[navi popViewControllerAnimated:YES];
XCTAssertEqual(navi.topViewController, controllerA);
}如果我将navi popViewControllerAnimated:YES更改为navi popViewControllerAnimated:NO,则可以正常工作。我也不知道原因。
发布于 2014-11-14 06:49:44
最好在创建视图后再调用popViewControllerAnimated。因此您可以创建NavigationController的子类,并像这样实现它。
- (void)init {
self = [super init];
if (self) {
UIViewController *controllerA = [[UIViewController alloc] initWithNibName:nil bundle:nil];
UIViewController *controllerB = [[UIViewController alloc] initWithNibName:nil bundle:nil];
self.viewControllers = @[controllerA, controllerB];
}
return self;
}
- (void)viewWillAppear {
[self popViewControllerAnimated:YES];
}发布于 2014-11-29 14:20:54
这是因为动画在另一个线程上异步发生。弹出视图控制器的动画只需要很少的时间,但测试断言是在动画完成之前进行的,因此topViewController尚未更改。
对此进行测试的最佳方法是模拟UINavigationController并验证是否调用了popViewController:YES。
发布于 2016-08-26 12:57:42
当推送是动画时,我在测试pushViewController时也遇到了类似的问题。
我能够通过将断言包装在这个来自matt的方便的delay函数中来解决这个问题。
在测试中引入延迟时,有必要使用ensure来确保检查断言。否则,测试在延迟代码执行之前完成,导致通过的测试不会检查您的断言!
// code to push the view controller goes here...
// set up the expectation
let expectation = expectationWithDescription("anything you want")
// now, assert something about the navigation controller
// after waiting 1/10th second for the animation to finish
delay (0.1) {
// for example: Navigation controller should have the
// expected number of view controllers
XCTAssertEqual(1, navigationController.viewControllers.count)
// if we get this far, then assertions passed and we must
// fulfill expectations to pass the test
expectation.fulfill()
}
// wait longer than the delay value, so the code in the delay closure
// has time to finish
waitForExpectationsWithTimeout(0.2, handler: nil)https://stackoverflow.com/questions/26918564
复制相似问题