【问题标题】:How to unit test a method which uses spring retry mechanism如何对使用弹簧重试机制的方法进行单元测试
【发布时间】: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


    【解决方案1】:
    @InjectMocks
    StudentServiceImpl classUnderTest;
    

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

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      相关资源
      最近更新 更多