简体   繁体   English

Kotlin 的“as”转换运算符如何影响分支覆盖率?

[英]How does Kotlin's "as" cast operator affect branch coverage?

How can I achieve branch coverage for an expression in which the "as" casting has been used, in this code for the expression errorCode = result.data as Int如何在表达式errorCode = result.data as Int的代码中实现使用“as”转换的表达式的分支覆盖

在此处输入图像描述

This bug fix in the Jacoco (version0.8.8 Changelog ) coverage tool offers an explanation: Jacoco(version0.8.8 Changelog )覆盖工具中的这个错误修复提供了解释:

Branch added by the Kotlin compiler version 1.6.0 and above for "unsafe" cast operator is filtered out during generation of report (GitHub 1266 ) Kotlin 编译器版本 1.6.0 及更高版本为“不安全”转换运算符添加的分支在报告生成期间被过滤掉 (GitHub 1266 )

Thus, the Kotlin compiler may generate a hidden branch for the cast (checking whether the cast is possible at all) which then surfaces in the coverage tool used.因此,Kotlin 编译器可能会为转换生成一个隐藏分支(检查转换是否可能),然后在使用的覆盖工具中出现。

From a functional perspective, you may want to add a test case that covers the situation that result.data doesn't contain an int.从功能的角度来看,您可能想要添加一个测试用例来涵盖result.data不包含 int 的情况。 That would probably lead to full coverage of the cast statement as well.这也可能导致演员声明的全面报道。

Though I am not a Kotlin developer, the unsafe cast raises the following questions:虽然我不是 Kotlin 开发人员,但不安全的演员表提出了以下问题:

  1. The null != errorCode check suggests that errorCode is of type Int? null != errorCode检查表明errorCodeInt? and not of type Int which can never be null.而不是Int类型,它永远不会是 null。
  2. This also suggests the type cast can be safe, via result.data as? Int这也表明类型转换可以是安全的,通过result.data as? Int result.data as? Int , where the as? result.data as? Intas? operator returns null on failure.运算符在失败时返回 null。
  3. Interestingly the coverage of your null != errorCode if-condition suggests that both the true and false branch are covered.有趣的是,你的null != errorCode if-condition 的覆盖范围表明 true 和 false 分支都被覆盖了。 I doubt this is the case.我怀疑是这种情况。 Instead, the compiler may have concluded that the condition can never be false (since errorCode has the non nullable type Int ), and therefore optimized the else branch away.相反,编译器可能已经得出结论,条件永远不会为假(因为errorCode具有不可为 null 的类型Int ),因此优化了 else 分支。

In other words, switching to Int?换句话说,切换到Int? and as? as? will likely move the reported uncovered branch to your null != errorCode if-condition, where it makes more sense.可能会将报告的未覆盖分支移动到您的null != errorCode if-condition,这样更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM