永远不会执行的Swift Switch Default case

3

所以,这是关于Swift的一点小问题,因为我正在尝试在我的测试中达到100%的代码覆盖率,但是Swift需要一行代码,这行代码将永远不会被执行 出于设计考虑

有问题的代码:

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")
    }
}

默认情况必须存在,因为Swift编译器要求针对类型(在这种情况下是Int)的每个潜在值都有一个case,但是无法针对默认情况编写测试。

在这种情况下,如何获得完整的单元测试覆盖率?


3
我很好奇在追求100%测试覆盖率之前,你会愿意实施多少血腥的变通方法来达成目标,直到你意识到这样做是多么低效。 - Alexander
有一个关于 switch! 语句的建议,其中包含一个 隐式default: fatalError(),请参见 https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20161003/027563.html。据我所知,这个建议并没有得到普遍认可。 - Martin R
1
看看你上面的例子,你将一个在0..<7范围内的整数映射到基于该整数在0..<7中的值计算(甚至是固定返回?)。如果这不仅是为了涵盖无法访问代码的问题而提供的示例,那么你可能希望将此函数重构为更简洁但仍具有相同语义价值的内容。(如何计算“适当的整数”?) - dfrib
Alexander:有一个点是,是的,完全覆盖不是必要的,但在这种情况下,它揭示了一种可能存在其他编写代码的方法,正如其他人所建议的那样。还要注意,这个问题是针对 Swift 编译器的小毛病,它做了许多其他直观的事情,但在这种情况下并不理解 switch 中的值映射到某个范围。默认情况永远不会发生,所以为什么我需要编写它呢?这打开了一整套其他的问题。编译器能否理解它?它将来会吗?等等… - promacuser
1个回答

3
这是我能想到的最佳解决方案:
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%测试覆盖率的问题,但它有很多缺点。当你想添加一个新的案例.seven时,你必须在枚举和开关语句中都添加一个新的案例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接