swift - for 循环内的代码覆盖率不正确

标签 swift xcode unit-testing code-coverage

你好溢出的 friend 们,

我正在开发一个 Swift 类,它的初始化程序包含一个 for 循环,该循环根据 init 的参数运行一定次数。不幸的是,我无法向您展示确切的代码,但它与此类似:

init(numberOfTimes: Int) {
    ...
    for index in 0..<numberOfTimes {
        // do some stuff here
        // shows 0 coverage
    }
    ...
}

我对这个初始化程序有几个单元测试,运行 for 循环 0 到 5 次。测试通过了,但代码覆盖率始终将循环的内部标记为未覆盖,即使它明显运行 — 我可以在循环内设置断点,循环中调用的每个函数都显示为已覆盖。

此外,如果我提取 for 循环的内容,代码确实看起来被覆盖了,类的整体代码覆盖率增加了将近 20%:

init(numberOfTimes: Int) {
    ...
    for index in 0..<numberOfTimes {
        doOne(index)
        // this part still shows 0 coverage
    }
    ...
}

private func doOne(_ index: Int) {
    // do same things here
    // shows correct coverage
}

为什么会这样?我是否没有满足 for 循环内代码覆盖率的正确标准?

最佳答案

我相信这可能是您正在谈论的错误:

https://bugs.swift.org/browse/SR-7446

Since upgrading to Xcode 9.3/Swift 4.1, I noticed that code coverage percentage dropped in several of my projects.

The bug seems to occur when I use conditional code within an initializer...

修复于:

https://github.com/apple/swift/pull/15966

This scheme of using a designated constructor for profiling purposes is a bit brittle. One concrete issue with this is that swift ends up attempting to create distinct SILProfilers for different constructors of a nominal type, and stored property initializers we want coverage for may not be emitted in the designated constructor.

A simpler idea is to store a map from nominal types to SILProfilers, and to then create a single merged profiler instance for all constructors of a nominal type.

关于swift - for 循环内的代码覆盖率不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50219759/

相关文章:

ios - 动态改变UIPageControl.appearance的点的背景颜色

ios - 调用自定义 Segue 类执行方法,操作不执行任何操作

javascript - 如何调用在不同文件中导入的对象内部的方法

c# - 使用 TypeMock 验证是否未调用具有特定参数的方法

ios - 运行带有分发配置文件的 xcode 项目

php - 使用 PHPunit 删除构造函数中的依赖项

swift - 如何在按钮焦点上执行 tvOS 中的 Action 事件

ios - 如何访问主UIViewController中嵌入父collectionViewCell中的collectionView?

ios - 在 Swift 中调用 Slack Webincoming 钩子(Hook)但得到 "interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

ios - Swift 枚举 : normal/non failable initializers not supported - or just broken?