Swift - 单元测试私有变量和方法 [英] Swift - Unit testing private variables and methods
问题描述
我正在尝试测试一门课程,但我对要测试的内容有些困惑.这是我要单元测试的类:
I'm trying to test a class but I'm kind of confused as to what to test. Here is the class I want to unit test:
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
}
}
}
对于上面的代码,什么是好的测试.
For the code above, what would be good tests.
是否值得测试字典operations
中的每一个操作(+、-、*、/等)?
Is it worth testing every single operation (+, -, *, /, etc) in the dictionary operations
?
是否值得测试私有方法?
Is it worth testing the private methods?
推荐答案
您不能使用 @testable
在 Swift 中测试私有方法.您只能测试标记为 internal
或 public
的方法.正如文档所说:
You can't test private methods in Swift using @testable
. You can only test methods marked either internal
or public
. As the docs say:
注意:@testable 只提供对内部"函数的访问;私有"声明在他们的文件之外是不可见的,即使使用@testable.
Note: @testable provides access only for "internal" functions; "private" declarations are not visible outside of their file even when using @testable.
阅读更多此处
这篇关于Swift - 单元测试私有变量和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!