测试在私有变量中保留其状态的类 [英] Testing a class which preserves its state in private variables
问题描述
我正在为我的班级编写单元测试.这个类在一些 private
变量(我不想公开)中保留它的状态.所以场景是:
I am writing unit tests for my class. This class preserves its state in some private
variables (which I don't want to expose publicly). So the scenario is:
- 如果我调用一个方法,它会在第一次将这个状态保存在
private
属性中,并调用一个委托方法并得到一些结果. - 当我第二次调用相同的方法时,输出将与之前的输入不同.
- If I call a method, the first time it will keep that state in
private
properties and call a delegate method with some result. - When I call the same method a second time, the output will be different on the basis of the previous input.
我想在我的测试中涵盖所有情况.
I want to cover all the cases in my tests.
- 一种简单的方法是将我的私有属性更改为公共属性,以便我可以在单元测试中模拟之前的输入.
- 另一种方法是在同一个测试中使用不同的输入调用同一个方法两次.第一次调用将保持状态,而下一次调用将进行实际测试.
但这两种方式对我来说都很尴尬,我不确定哪种方式最好.为此类编写单元测试的最佳方法是什么?
But both these ways seem awkward to me, and I am not sure of the best one. What is the best way to write unit test for this class?
protocol ZoneUpdateDetectorOutput: class {
func updateZoneState(_ state: ZoneState)
}
class ZoneUpdateDetector {
var zoneChangeTimer: TimerProtocol?
weak var delegate: ZoneUpdateDetectorOutput?
private var previousZoneState: ZoneState?
private var expectedZoneState: ZoneState?
private func updateZoneState() {
// If `expectedZoneState` is not equal to `previousZoneState` then `delegate` will be called
// Otherwise it will just skip
if expectedZoneState != previousZoneState {
delegate?.updateZoneState(expectedZoneState!)
previousZoneState = expectedZoneState
}
}
private func runNotifyZoneStateTimer() {
guard zoneChangeTimer?.isValid() == false else {
return
}
zoneChangeTimer?.start(timeInterval: 5,
onFire: { [weak self] in
guard let strongSelf = self else {
return
}
// On timer fire, it will try to update the state
strongSelf.updateZoneState()
})
}
// When zone changes, this method is invoked
// I basically want to test this method
func zoneStateChanged(_ state: ZoneState) {
expectedZoneState = state
if state != .inZone {
runNotifyZoneStateTimer()
} else {
zoneChangeTimer?.stop()
}
}
}
推荐答案
经过与一些专家的研究和讨论,我想出了一个解决方案,如果我们想测试一个保留其状态的类,那么保留其状态的功能状态应该属于一个单独的类.这与将变量设置为私有的目的相同.因此,ZoneUpdateDetector
应该有一个依赖项,例如:ZoneUpdateStatePreserver
并且它应该保持之前在 ZoneUpdateDetector
After researching and discussing with some experts, I come up with the solution that if we want to test a class which preserve it's state then the functionality which is preserving the state should go under a separate class. Which will serve the same purpose as setting the variables as private. So, ZoneUpdateDetector
should have a dependency for example: ZoneUpdateStatePreserver
and it should keep the state which was previously inside ZoneUpdateDetector
这篇关于测试在私有变量中保留其状态的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!