如何测试自定义 UINavigationController 行为

How do I test custom UINavigationController behaviour

我正在尝试在我的测试中测试一些 UINavigationController 自定义子 class 委托行为,但委托方法从不在测试中触发。我已经尝试将 appdelegate window rootViewController 设置为导航并访问 .view 属性 但是推送视图控制器永远不会触发 willShow 委托方法。

在非测试应用程序(运行 应用程序和导航)上调用它。

这是一个代码示例:

let firstController = UIViewController()
let secondController = UIViewController()
let navigationController = BurgerNavigationController(rootViewController: firstController)
navigationController.pushViewController(secondController, animated: true)
expect(secondController.navigationItem.backBarButtonItem).notTo(beNil())

我希望导航控制器调用它是

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {

委托方法。它在 运行 应用程序时被调用,但我不知道如何测试它。

这是我正在使用的 UINavigationController 的自定义初始化:

override init(rootViewController: UIViewController) {
    super.init(rootViewController: rootViewController)
    delegate = self
}

并且实现了委托方法但从未在同一个方法中调用 class:

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    //Code here never called on tests but called on real app
}

我发现了问题。 UINavigationController 委托是异步的,因此您应该等待它被调用。

在我的例子中,我使用 Nimble 进行测试,所以使用 .toEventually 而不是 .to 是可行的。它现在等待期望成真。