@SpringBootTest
class StudentRepositoryTest {
@Autowired
Student student;
@Autowired
StudentGrades studentGrades;
@MockBean
private StudentRepository studentRepository;
@Autowired
private StudentService studentService;
@Autowired
private ApplicationContext context;
@DisplayName("Throw runtime error")
@Test
void throwRuntimeError() {
Student nullStudent = (Student)context.getBean("Student");
doThrow(new RuntimeException()).when(studentRepository).checkNull(nullStudent);
assertThrows(RuntimeException.class, ()-> {studentService.checkNUll(nullStudent); });
verify(studentRepository, times(1)).checkNull(nullStudent);
}
@DisplayName("Multiple Stubbing")
@Test
void stubbingConsecutiveCalls() {
Student nullStudent = (Student)context.getBean("Student");
when(studentRepository.checkNull(nullStudent))
.thenThrow(new RuntimeException())
.thenReturn("Do not throw exception second time");
assertThrows(RuntimeException.class, ()->{studentRepository.checkNull(nullStudent);});
assertEquals("Do not throw exception second time", studentService.checkNull(nullStudent));
verify(studentRepository, times(2)).checkNull(nullStudent);
}
}