首页 > 解决方案 > 如何对使用弹簧重试机制的方法进行单元测试

问题描述

我正在尝试编写一个使用 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

标签: springjunitmockitospring-testspring-retry

解决方案


@InjectMocks
StudentServiceImpl classUnderTest;

您将其作为 Mock 注入,而不是使用 Spring@Autowired来通过重试拦截器获取完整的 Spring 代理。


推荐阅读