gpt4 book ai didi

Swift - 单元测试私有(private)变量和方法

转载 作者:IT王子 更新时间:2023-10-29 05:02:25 25 4
gpt4 key购买 nike

我正在尝试测试一个类,但我对测试什么感到困惑。这是我要进行单元测试的类:

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 中的每个操作(+、-、*、/等)?

是否值得测试私有(private)方法?

最佳答案

您不能使用 @testable 测试 Swift 中的私有(private)方法。您只能测试标记为 internalpublic 的方法。正如文档所说:

Note: @testable provides access only for “internal” functions; “private” declarations are not visible outside of their file even when using @testable.

阅读更多 here

关于Swift - 单元测试私有(private)变量和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37421235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com