首页 > 解决方案 > 存在如何使用 NavigationalController 对 Segue 进行单元测试

问题描述

我正在尝试编写一个测试来检查presentModally segue是否被解除或使用navigationController呈现。MessageVC 是我想测试它是否存在或关闭的模式。但是performSegue之后,topViewController并没有变成MessageVC。

联系情节提要控制器(ContactViewController):

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    switch segue.identifier {

    case "Message":
        let navigationController = segue.destination as! UINavigationController
        let messageVC = navigationController.topViewController as! MessageViewController

        // Set the modal view controller to be the delegate of the presentationController for this presentation,
        // so that modal view controller can respond to attempted dismissals
        navigationController.presentationController?.delegate = messageVC
    }

测试

var messageVC = MessageViewController()

override func setUp() {
    let storyboard = UIStoryboard(name: "Contact", bundle: Bundle.main)

    let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController

    navigationController.topViewController.performSegue(withIdentifier: "Message", sender: self)
}

func testModalPresent() {
}

标签: iosswiftxcodeios11xctest

解决方案


这很可能是由于您正在调用异步执行。在您的测试完成之前,它甚至可能没有机会执行。

有了这种东西,你真的有两个选择:

  1. 使用 XCTest 异步预期更新您的测试,以便它允许代码执行并等待预期结果。

  2. 将您的测试重新编写为 UI 测试。

任何一个都不会直截了当,取决于你的技能,它对你的效果如何。但是,如果您还不了解它们,这两种技术都值得学习。

测试预期将在许多异步情况下为您提供帮助 - 网络代码、异步 API(如 Promise、响应式和 Apple 的 Combine)。

UI 测试将有助于确保您的应用程序从用户的角度来看符合预期。


推荐阅读