我模拟了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));
}
聚 甲醛:
<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语句仍然显示它没有被测试覆盖。
可能的原因是什么?
参考
具有Jacoco代码覆盖率的PowerMockito
https://www . igorkromin . net/index . PHP/2018/02/20/jacoco-reports-missing-code-coverage-for-tests-using-power mock/
https://github.com/mockito/mockito/issues/969
就我的理解,< code>employeeService对象保留了一个模拟:
我用Spring启动服务嘲笑过
这意味着你的测试没有测试任何东西。为什么?测试代码仅与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);
雇员服务
对象不是模拟,而是雇员服务类的实例。第一个结构是调用get雇员详细信息
方法。第二个不这样做。该方法是在Mockito“配置对象上调用的,而不是在雇员服务
对象上调用的(没有直接执行=没有真正的方法调用)。
我想在android项目中生成JUnit测试的代码覆盖率报告,所以我添加了JaCoCo gradle插件。这是我的项目级文件: 它通过运行<code>工作得很好/gradlew JacoFullReport。但不幸的是,使用<code>RobolectricTestRunner@RunWith注释的测试,或者使用运行的测试报告覆盖率很好。 任何帮助都将不胜感激来解决这个问题。 更新1:我注意到我应
您好,我正在尝试使用PostConstruct方法初始化字段,但在测试中,此方法不会填充bidiMap字段。 有没有办法模拟字段,它是的字段? 测试: 正在测试的类:
我正在为我的项目设置Jacoco Gradle插件。该插件执行良好,并生成覆盖报告,但它不排除我将排除的包。 我想包含的类在com/xxx/ws/hn/**中,我想排除的类在com/xxx/ws/企业/**中。 这是我的Gradle脚本: 我有什么遗漏吗?我尝试过各种排除模式,包括“.”包的分隔符,而不是“/”,但似乎没有任何效果。任何帮助都将不胜感激。
我有下面一个班的方法。 使用mockito的junit测试用例将提供100%的代码覆盖率。
我正在springboot应用程序中编写Junits,它只有一个初始化器类 以及其他控制器和服务类。 服务类的Junit如下所示: 当我运行Junit时,它会抛出如下错误: 我还尝试了所有注释,如,@ContextConfiguration(classes=Initializer.class),,但它仍会抛出相同的错误。代码中没有其他类似于应用程序上下文的配置类。
我是scala新手,junit测试用例不在集成测试中运行。 我在build.sbt中添加了 请帮助我运行集成测试