如何让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
相关产品推荐
相关产品推荐

