【问题标题】:Unit testing methods which update UI elements in iOS在 iOS 中更新 UI 元素的单元测试方法
【发布时间】:2019-04-17 12:00:02
【问题描述】:

我正在尝试为我现有的代码编写单元测试。 我有 3 种方法。

func methodOne() {
    // code
    methodTwo()
}

func methodTwo() {
    // code
    methodThree()
}

func methodThree() {
    // code
    // update UI element
}

对这些方法进行单元测试的理想方法是什么。在单元测试methodTwo() 时,它调用methodThree(),因为未加载UI 元素,当调用methodThree() 时它们具有nil 值。如何对涉及 UI 元素的方法进行单元测试。我不想测试UI元素是否加载正确,我只想测试methodTwo()和methodThree()中的代码。有没有办法绕过 UI 元素相关的代码。任何帮助表示赞赏。谢谢。

【问题讨论】:

  • 你尝试过 UI 测试吗?
  • 那我将无法测试methodTwo()。我不想在这里测试任何与 UI 相关的代码。我只想测试methodTwo()和methodThree()中的代码。

标签: ios swift unit-testing


【解决方案1】:

做到这一点的最佳方法是尽可能将要测试的代码与 UI 分开。这可以通过将methodTwo 的//code 部分放入它自己的函数(即methodFour)并从methodTwo 调用它来完成。那么您的代码将如下所示:

func methodTwo() {
     methodFour()
     methodThree()
}

func testMethodFour() {
     methodFour()
     // check assumptions
}

func methodFour() {
     // code that you originally had in methodTwo before methodThree
}

【讨论】:

    【解决方案2】:

    嗨@Pradeep?,欢迎来到 StackOverflow。

    从您描述您遇到的失败的方式来看,我猜您的方法是UIViewController 中的@IBOutlets,对吗?

    如果是这种情况,您可以让测试初始化​​ UIViewController 视图,方法是在调用依赖于可用视图的方法之前执行以下操作:

    _ = viewControllerUnderTest.view
    

    或

    viewControllerUnderTest.beginAppearanceTransition(true, animated: false)
    

    This 是一篇不错的帖子,可以了解更多关于测试的陷阱UIViewControllers,this 有一个更高级的方法,如果你最终编写了大量依赖于视图的测试,可以帮助你,比如你描述的。

    不过,我鼓励您尽量避免使用 UIViewControllers 和 UIViews 的业务逻辑代码。这些类的生命周期使它们的测试变得更加棘手,而且您可以用最简单的方式进行更好的测试。

    将所有业务逻辑写在专用的classes 和structs 中,如果它们不子类化其他类型,它们将更容易测试。仅使用UIViewControllers 作为胶水代码向用户显示数据并将他们的输入转发到您的业务逻辑,因此您只需编写一些简单的测试。保留UIViews humble,只有配置它们的逻辑。

    (如果我的 UIViewController 猜测有误,请添加更多详细信息,我们会想办法让您的测试不崩溃。)

    【讨论】:

    • 我现在使用模拟作为解决方法。我稍后会检查您的建议。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    相关资源
    最近更新 更多