2
Swift에 대한 약간의 단서가 있습니다. 테스트에서 100 % 코드 범위에 도달하려고하지만 Swift는 절대로 도달하지 않을 코드 라인을 필요로합니다 디자인에 의해.Swift Switch 절대로 실행되지 않는 기본 케이스
기분을 상하게하는 코드 : 스위프트 컴파일러 (이 경우, 지능의) 유형의 모든 잠재적 가치에 대한 사례를 필요로하기 때문에
func calculateWorkingOffset(_ offset: Int) -> Int {
let translatedOffset = abs(offset) % 7
switch translatedOffset {
case 0:
return [appropriate_integer]
case 1:
return [appropriate_integer]
case 2:
return [appropriate_integer]
case 3:
return [appropriate_integer]
case 4:
return [appropriate_integer]
case 5:
return [appropriate_integer]
case 6:
return [appropriate_integer]
default:
fatalError("Should never be executed")
}
}
가 기본 케이스가 존재해야하지만 쓸 수있는 방법은 없습니다 디폴트의 경우에 대한 테스트.
전체 단위 테스트 커버리지를 얻으려면이 경우 가장 좋은 방법은 무엇입니까?
func calculateWorkingOffset(_ offset: Int) -> Int {
switch Offset(rawValue: abs(offset) % 7)! {
case .zero:
return [appropriate_integer]
case .one:
return [appropriate_integer]
case .two:
return [appropriate_integer]
case .three:
return [appropriate_integer]
case .four:
return [appropriate_integer]
case .five:
return [appropriate_integer]
case .six:
return [appropriate_integer]
}
}
// Please name this enum and its values appropriately. I called it
// Offset because I have no context of what you're doing
enum Offset: Int {
case zero
case one
case two
case three
case four
case five
case six
}
이 100 % 테스트 커버리지의 문제를 해결할 수 있지만 :
나는 카운터 생산성이 얼마나 좋은지를 결정하기 전에 100 % 테스트 커버리지를 구현하기 위해 얼마나 많은 고민을해야하는지 궁금합니다. – Alexander
'switch!'문에 대한 제안이있었습니다. * 암시적인 *'default : fatalError()'를 가지고 있습니다. https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20161003/027563.html을보십시오. 내가 이해하는 한, 이것은 일반적으로 승인되지 않았습니다. –
위의 예를 보면 '0 .. <7'의 정수 값을 기준으로'0 .. <7' 범위의 정수를 계산 (또는 fix-return?)에 매핑 할 수 있습니다. 이것이 도달 할 수없는 코드의 문제를 다루기위한 단순한 사례가 아닌 경우이 기능을 간단하게하지만 여전히 동일한 의미 론적 가치를 지니고있는 것으로 리팩토링하는 것이 좋습니다. ('적합한 정수'는 어떻게 계산됩니까?) – dfri