You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Jacoco忽略含Gson @SerializedName注解的类以避免覆盖率失败?

解决Jacoco忽略带@SerializedName注解类的方法

方案1:通过Gradle配置过滤带指定注解的类

Jacoco支持在构建脚本中配置规则,直接排除带有@SerializedName注解的类。在项目的Gradle脚本中,找到jacocoTestCoverageVerification和jacocoTestReport块,添加如下过滤规则:

// 覆盖率校验时排除带@SerializedName的类
jacocoTestCoverageVerification {
    violationRules {
        rule {
            excludes = [
                '**/*@com.google.gson.annotations.SerializedName*'
            ]
        }
    }
}

// 覆盖率报告中也排除这些类
jacocoTestReport {
    reports {
        xml.required = true
        html.required = true
    }
    excludes = [
        '**/*@com.google.gson.annotations.SerializedName*'
    ]
}

方案2:给数据类添加@Generated注解自动忽略

Jacoco默认会忽略标记了@Generated注解的类,你可以直接给CloseLotDto加上该注解:

import com.google.gson.annotations.SerializedName
import javax.annotation.Generated
import java.util.Date

@Generated("Gson序列化类")
internal data class CloseLotDto(
    @SerializedName(value = "id") val closeLotId: String?,
    @SerializedName(value = "user_id") val userID: Long,
    @SerializedName(value = "address") val address: String,
    @SerializedName(value = "date_from") val dateFrom: Date,
    @SerializedName(value = "date_to") val dateTo: Date,
    @SerializedName(value = "point_of_interaction") val pointOfInteraction: PointOfInteractionDto,
    @SerializedName(value = "identification") val identification: String?,
    @SerializedName(value = "contents") val contents: List<SubContentDto>,
)

如果项目缺少@Generated依赖,在Gradle中添加:

testImplementation 'javax.annotation:javax.annotation-api:1.3.2'

方案3:直接按类路径精准排除

如果上述注解过滤不生效,可直接指定类的全路径进行排除:

jacocoTestCoverageVerification {
    violationRules {
        rule {
            excludes = [
                '你的包路径/CloseLotDto'
            ]
        }
    }
}

内容的提问来源于stack exchange,提问作者Pierre Vieira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:50:24