Sur*_*alu 3 java exception mockito spring-boot junit5
在我的业务逻辑中,我没有任何异常场景,不确定如何测试 sprint boot Service 类中的 catch 块。大多数场景都是在控制器级别处理的。
但对于声纳覆盖范围,我也需要在我的服务中覆盖捕获块。
我的示例代码就像
public void employeeDetails(Object Employee) throws CustomException {
try {
int count = commonUtils.calculateEmployeeCount(Employee)
} catch (Exception e) {
throw new CustomException(" Exception occurred", e);
}
}
Run Code Online (Sandbox Code Playgroud)
我的业务逻辑是否应该有任何故障场景需要测试,或者我们可以选择模拟自定义虚拟异常以进行测试。请任何人就此提出建议。
参考
我假设一个类使用方法EmployeeServiceImpl
实现。请注意,根据代码约定,方法名称以小写字母开头,因此我将在回答中遵循这样的约定。EmployeeService
void EmployeeDetails(Object Employee)
public void employeeDetails(Object employee) throws CustomException {
try {
int count = calculateEmployeeCount(employee)
} catch (Exception e) {
throw new CustomException("Exception occurred", e);
}
}
Run Code Online (Sandbox Code Playgroud)
您需要实现calculateEmployeeCount
抛出异常的方法,该异常可以是Exception
. 为此,您需要具有此类方法的类的实例。该实例应该使用模拟@MockBean
,或者如果是我们的EmployeeServiceImpl
,则用于@SpyBean
部分模拟,而不是@Autowired
用于带有注入 Bean 的生产 Bean,并且测试 Bean 优先于@MockBean
生产 Bean。
假设您使用 Spring 测试启动器和 Mockito 以及具有方法的同一calculateEmployeeCount
类(从其名称来看)。
@SpyBean
private EmployeeService employeeService;
Run Code Online (Sandbox Code Playgroud)
Mockito.when(employeeService.calculateEmployeeCount())
.thenThrow(new Exception("An exception"));
Run Code Online (Sandbox Code Playgroud)
最后一步是验证是否被CustomException
抛出:
Object employee = new Object(); // it doesn't need to be a mock
CustomException exception = Assertions.assertThrows(
CustomException.class,
() -> employeeService.employeeDetails(employee));
// the thrown exception is available fur further testing (of the message, cause etc.)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4996 次 |
最近记录: |