How to unit test a method which uses spring retry mechanism

Viewed 574

I am trying to write a Junit method that uses the spring retry mechanism to re-invoke a failed operation. But I am not able to verify spring retry working properly with 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
1 Answers
@InjectMocks
StudentServiceImpl classUnderTest;

You are injecting it as a Mock instead of using Spring @Autowired to get the full Spring proxy with the retry interceptor.

Related