swift - 如何使用 spy 对 textView 进行单元测试

标签 swift unit-testing mocking stub spy

我有一个包含 textView 的单元格,我想使用单元测试测试该 textView 的属性是否设置正确。但是,在测试中访问私有(private)的 textView 时,我似乎遇到了障碍。

有什么方法可以测试我的 textView:-

这是我的代码

class MyCell {

  private let myText: UITextView = {
      let textView = UITextView()
      textView.isScrollEnabled = false
      textView.isEditable = false

      return textView
    }()

  func setup(viewModel: MYViewModel) {

      if viewModel.someValue {
          myText.backgroundColor = UIColor.red
      } else {
          myText.backgroundColor = .clear
      }

    }
}

是否可以测试类似 testView 的背景颜色设置为清除的东西?

最佳答案

除非你想放宽myText的访问级别来自 privateinternal (如果您不指定,则为默认值),没有直接方法来测试它。

我必须间接测试的唯一建议是使用 snapshot testing .

您可以编写两个快照测试,一个对应 .someValue 的每个值来自你的 MYViewModel .

另一种使 View 的测试和可维护性变得简单的方法是引入 ViewConfiguration值类型,遵循 humble view模式。

基本上,你可以有一个 structMYViewModel之间和 MyCell描述了 MyCell 的每个 View 属性.

struct MyCellViewConfiguration {
  let textFieldBackgroundColor: UIColor
}

extension MYViewModel {

  var viewConfiguration: MyCellViewConfiguration = {
    return MyCellViewConfiguration(
      textFieldBackgroundColor: someValue ? .red : .clear
    )
  }
}

extension MyCell {

  func setup(with configuration: MyCellViewConfiguration) {
    myText.backgroundColor = configuration.textFieldBackgroundColor
  }
}

setup(with configuration: MyCellViewConfiguration)中的代码非常简单——只是一个 1 对 1 的分配——你无需测试就可以逃脱。

然后您可以为 MyCellViewConfiguration 编写测试从 MYViewModel 计算得出.

关于swift - 如何使用 spy 对 textView 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55877641/

相关文章:

Java 域类填充数据

ios - 条形按钮导航 Controller 隐藏 Swift

java.lang.AssertionError : Response content

python - 编写扩展Python单元测试的自定义fail()方法

reactjs - Jest/ enzyme |在 componentDidMount 中测试函数调用

unit-testing - 我应该为所有内容编写单元测试吗?

ios - 处理滑动删除 Firebase 数据

ios - 如何将 Objc 文件导入到我的自定义 cocoapods 框架中的 Swift 文件中?

ios - 从 Swift 函数中的异步调用返回数据

python - 如何使用 unittest.mock.MagicMock 或 Mock 类模拟 `name` 属性?