[英]How to get test coverage or ignore by Jacoco for Kotlin data classes
Jacoco對Kotlin的數據類別的覆蓋率為0%。 如何配置它來測量覆蓋率或忽略數據類?
我正在為數據模型類的自動生成代碼尋找相同測試覆蓋問題的解決方案,並偶然發現:
Kotlin + JaCoCo:調整編譯器以跳過生成的代碼
解決方案:將 JaCoCo插件更新為0.8.2並解決您的問題。
JaCoCo在0.8.2版本中解決了這個問題,請閱讀更改日志 -
雖然它並沒有真正回答你的問題,但你可以通過編寫涵蓋數據類生成的函數的測試來完全覆蓋jacoco中的數據類。
例如,假設有一個包含一個var
和一個val
的數據類
data class MyDataClass(var s1: String, val s2: String)
當我運行jacoco時,我發現它正在測量MyDataClass生成的以下內容的覆蓋范圍:
hashCode()
equals(Object)
toString()
MyDataClass(String, String)
copy(String, String)
setS1(String)
getS1()
getS2()
component1()
component2()
涵蓋大部分內容的單元測試可能是:
@Test
fun testCodeCoverageForMyDataClass() {
// call the constructor
val tested = MyDataClass("original s1", "original s2").apply {
// call the setters
s1 = "new s1"
// call the getters
assertEquals("new s1 original s2", "$s1 $s2")
// call toString()
assertEquals("MyDataClass(s1=new s1, s2=original s2)", "$this")
// call componentN() functions
val (res1, res2) = this
assertEquals("new s1 original s2", "$res1 $res2")
}
// call copy()
val testedCopy = tested.copy(s2 = "new s2").apply {
// call equals()
assertNotEquals(this, tested)
// call hashCode()
assertNotEquals(this.hashCode(), tested.hashCode())
}
}
我知道,這是一種痛苦,但在有支持之前,這有助於我完成覆蓋。
如果您將數據類放在特定包或特定文件中,則可以將它們從classDirectories
排除。 在下面的示例中,我將數據類放在**/model/**
:
task kotlinJacocoTestReport(type: JacocoReport, dependsOn: 'test') {
reports {
html.enabled = true
html.destination = "${buildDir}/reports/jacoco"
}
sourceDirectories = files(["${project.projectDir}/src/main/kotlin"])
classDirectories = fileTree(dir: "${buildDir}/classes/kotlin/main", excludes: ['**/model/**'])
executionData = files("${buildDir}/jacoco/test.exec")
}
使用插件,如下所示: 生成Kotlin插件
該插件通過在幕后添加@lombok.Generated注釋,從代碼覆蓋中刪除所有合成的Kotlin生成的代碼(自動獲取器和設置器,並且應該干凈地覆蓋您的數據類)。
請注意,您必須使用Jacoco 0.8或更高版本才能工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.