【问题标题】:JaCoCo does not work for Mockito test casesJaCoCo 不适用于 Mockito 测试用例
【发布时间】:2021-02-22 03:47:44
【问题描述】:

我已经模拟了 Spring Boot 服务类来测试 catch 块语句。我的示例测试用例如下:

@SpyBean
private EmployeeService employeeService;

@Test
public void employeedetails() throws CustomException {
    Employee employee= new Employee();
    Mockito.when(employeeService .getEmployeeDetails(employee))
           .thenThrow(new CustomException("Exception while getting the employee details"));

    CustomException exception = Assertions.assertThrows(
        CustomException.class,
        () -> employeeService.getEmployeeDetails(caution));
}

POM:

<build>
  <plugins>
    <plugin>
      <groupId>org.jacoco</groupId>
      <artifactId>jacoco-maven-plugin</artifactId>
      <executions>
        <execution>
          <id>aggregate-coverage-reports</id>
          <phase>test</phase>
          <goals>
            <goal>report-aggregate</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

测试用例执行良好,但未反映在 Java 代码覆盖率报告中。我的 catch 语句仍然显示它没有被测试覆盖。

可能是什么原因?

参考

PowerMockito with Jacoco Code Coverage

https://www.igorkromin.net/index.php/2018/02/20/jacoco-reports-missing-code-coverage-for-tests-using-powermock/

https://github.com/mockito/mockito/issues/969

【问题讨论】:

    标签: java code-coverage junit5 jacoco


    【解决方案1】:

    据我了解,employeeService 对象保持模拟:

    我已经被spring boot service嘲笑过

    这意味着你的测试没有测试任何东西。为什么?测试代码只与employeeService 对象交互。这意味着真正的服务实现没有被执行(根本没有测试)。如果您只想检查部分服务,则必须使用间谍:

    @Test
    public void employeedetails() throws CustomException {
        EmployeeService employeeService = Mockito.spy(new RealEmployeeServiceImpl(...));
        Employee employee = new Employee();
        Mockito.doThrow(new CustomException("Exception while getting the employee details"))
               .when(employeeService).getEmployeeDetails(employee)
    
        CustomException exception = Assertions.assertThrows(
                CustomException.class,
                () -> employeeService.getEmployeeDetails(caution));
    
        // rest of the test
    }
    

    什么很重要,结构

    Mockito.when(employeeService.getEmployeeDetails(employee))
           .thenThrow(new CustomException("Exception while getting the employee details"));
    

    已改为

    Mockito.doThrow(new CustomException("Exception while getting the employee details"))
           .when(employeeService).getEmployeeDetails(employee);
    

    employeeService 对象不是模拟对象,而是员工服务类的实例。第一个结构是调用getEmployeeDetails 方法。第二个不这样做。该方法在 Mockito 配置对象上调用,而不是在 employeeService 对象上调用(不直接执行 = 没有真正的方法调用)。

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多