我目前在我的项目中使用 jacoco maven 插件。我已经使用mockito 编写了单元测试。我已经阅读了 jacoco 常见问题解答、Google Groups 页面和 Jacoco github 问题线程,这些线程涉及在单元测试类中捕获合成成员字段并重新分配它们,因为 jacoco 注入(inject)的对象不知道如何处理合成成员。
然而,我的很多单元测试都是使用mockito框架设置和模拟的,我不认为Jacoco喜欢MockMvc对象类。我认为类本身是使用反射以某种方式实现的,这导致 jacoco 失败。
我运行 mvn test 时的错误是:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is my.project.submodule.controller.ControllerException: Unknown property '$jacocoData'
触发此问题的我的代码片段是:
mockMvc.perform(
get("/api/substituteStuff"))
.andExpect(jsonPath("$", hasSize(10)))
.andExpect(status().isOk())
最佳答案
I think the class itself is implemented somehow using reflection which is causing jacoco to fail.
在很多情况下编译器可以生成 synthetic members ,作为示例之一 - 类中存在断言。这会导致同样的失败,所以这不是 JaCoCo 失败,而是你的代码/库的失败。解决方案是更新您的代码或库以忽略此类成员。
引用http://www.jacoco.org/jacoco/trunk/doc/faq.html :
My code uses reflection. Why does it fail when I execute it with JaCoCo?
To collect execution data JaCoCo instruments the classes under test which adds two members to the classes: A private static field $jacocoData and a private static method $jacocoInit(). Both members are marked as synthetic.
Please change your code to ignore synthetic members. This is a good practice anyways as also the Java compiler creates synthetic members in certain situation.
作为解决方法 - 从检测中排除类。
关于java - 不确定如何捕获和重新分配类中的合成成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590748/