spring - 如何对使用弹簧重试机制的方法进行单元测试
问题描述
我正在尝试编写一个使用 spring 重试机制来重新调用失败操作的 Junit 方法。但我无法验证 spring 重试是否与 JUnit 一起正常工作。
public interface StudentService{
public void addStudent(Student student);
}
@Service
public class StudentServiceImpl {
@Autowired
SomeService someService;
@Transactional
// InternalServerErrorException runtime exception
@Retryable(value = {InternalServerErrorException.class},
maxAttempts=6)
public void addStudent(Student student){
try{
someService.addStudent(student);
}catch(Exception e){
throw new InternalServerErrorException("unable to add student");
}
}
}
@Configuration
@@EnableRetry
public class AppConfig{
}
//
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentServiceImplTest(){
@InjectMocks
StudentServiceImpl classUnderTest;
@Mock
SomeService someService;
public void testAddStudent(){
//ARRANGE
Student student= new Student("John","A123") // name, Id
doThrow(InternalServerErrorException).doNothing().when(someService).addStudent(student);
//ACT
classUnderTest.addStudent(student);
//ASSERT 1st attempt got exception , 2nd attempt success
// Always failed with exception
verify(someService, times(2)).addStudent(any());
}
}
// getting following exception
com.studentapp.exceptions.InternalServerErrorException: unable to add student
解决方案
@InjectMocks
StudentServiceImpl classUnderTest;
您将其作为 Mock 注入,而不是使用 Spring@Autowired
来通过重试拦截器获取完整的 Spring 代理。
推荐阅读
- javascript - 将 createObjectURL 的结果分配给图像无法在移动 Safari 上加载资源
- laravel - 如何使用 javascript 加载私有 Amazon S3 文件?
- javascript - 从剑道编辑器获取没有标记的文本
- c# - 如何将字符串资源文件导入表单的资源文件?
- python - Pandas:np.vectorize 更新数据帧中的值很慢
- python - matplotlib 产生的奇怪图像
- json - 解析 JSON 邮递员响应
- php - 如何使用 php 和 cookies 显示消息
- c - 带有 SWIG 的 Java 中具有动态数组的 C 结构
- javascript - 在切换到 selenium 中的帧之前等待脚本完成