【发布时间】:2020-07-20 18:25:44
【问题描述】:
我正在尝试编写一个使用 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
【问题讨论】:
标签: spring junit mockito spring-test spring-retry