본문 바로가기

Spring & Java

Spring boot Throwing Exception test

반응형
@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);
    }


}
반응형

'Spring & Java' 카테고리의 다른 글

Spring Boot Config Server  (0) 2023.09.29
Spring boot Private field and method Test  (0) 2022.05.22
Spring boot @MockBean  (0) 2022.05.22
Spring boot Mockito Example - @Mock & @InjectMocks  (0) 2022.05.22
Spring boot Test with Mockito  (0) 2022.05.22