【发布时间】:2016-05-24 18:29:14
【问题描述】:
我正在尝试测试一门课程,但我对要测试的内容有点困惑。这是我要单元测试的类:
class CalculatorBrain {
private var accumulator = 0.0
func setOperand(operand: Double) {
accumulator = operand
}
var result: Double {
return accumulator
}
private var operations: Dictionary<String, Operation> = [
"=" : .Equals,
"π" : .Constant(M_PI),
"e" : .Constant(M_E),
"±" : .UnaryOperation({ (op1: Double) -> Double in return -op1 }),
"√" : .UnaryOperation(sqrt ),
"cos": .UnaryOperation(cos),
"+" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 + op2 }),
"−" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 - op2 }),
"×" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 * op2 }),
"÷" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 / op2 })
]
private enum Operation {
case Constant(Double)
case UnaryOperation((Double) -> Double)
case BinaryOperation((Double, Double) -> Double)
case Equals
}
func performOperation(symbol: String) {
if let operation = operations[symbol] {
switch operation {
case .Constant(let value):
accumulator = value
case .UnaryOperation(let function):
accumulator = function(accumulator)
case .BinaryOperation(let function):
executePendingBinaryOperation()
pendingBinaryOperation = PendingBinaryOperationInfo(binaryOperation: function, firstOperand: accumulator)
case .Equals:
executePendingBinaryOperation()
}
}
}
private var pendingBinaryOperation: PendingBinaryOperationInfo?
private struct PendingBinaryOperationInfo {
var binaryOperation: (Double, Double) -> Double
var firstOperand: Double
}
private func executePendingBinaryOperation() {
if let pending = pendingBinaryOperation {
accumulator = pending.binaryOperation(pending.firstOperand, accumulator)
pendingBinaryOperation = nil
}
}
}
对于上面的代码,什么是好的测试。
是否值得测试字典 operations 中的每个操作(+、-、*、/ 等)?
是否值得测试私有方法?
【问题讨论】:
-
作为一名游戏程序员,我做的事情与单元测试不同,但它们对个人项目有很大帮助。例如:防范不存在的操作(debugAssert 和日志)。确保函数只能传入正确的范围。将默认值切换为“永远不会到达这里”断言。确定该安全性是否在函数或调用者上。那些总是在私人职能中工作。此外,如果您想为不存在的操作提供默认值,例如崩溃,请使用 TDD。但是 TDD 无法保护您免受生产缺陷的影响,就像默认和防范会为用户节省一次或十二次崩溃一样
标签: swift unit-testing