我有一个包含 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
的访问级别来自 private
至 internal
(如果您不指定,则为默认值),没有直接方法来测试它。
我必须间接测试的唯一建议是使用 snapshot testing .
您可以编写两个快照测试,一个对应 .someValue
的每个值来自你的 MYViewModel
.
另一种使 View 的测试和可维护性变得简单的方法是引入 ViewConfiguration
值类型,遵循 humble view模式。
基本上,你可以有一个 struct
在MYViewModel
之间和 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/