首页 > 解决方案 > 在 iOS 中更新 UI 元素的单元测试方法

问题描述

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

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

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

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

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

标签: iosswiftunit-testing

解决方案


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

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

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

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

推荐阅读