Skip to content

Instantly share code, notes, and snippets.

@singun
Created April 8, 2019 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singun/674d9d356afa226e69d2308e615afd6d to your computer and use it in GitHub Desktop.
Save singun/674d9d356afa226e69d2308e615afd6d to your computer and use it in GitHub Desktop.
throw exception
@Test
void testDoThrow() {
doThrow(new RuntimeException("throw")).when(visitRepository).delete(any(Visit.class));
assertThrows(RuntimeException.class, () -> service.delete(new Visit(1l)));
verify(visitRepository).delete(any(Visit.class));
}
@Test
void testFindByIdThrows() {
// given
given(visitRepository.findById(1l)).willThrow(new RuntimeException("throw"));
// when - none
// then
assertThrows(RuntimeException.class, () -> service.findById(1l));
verify(visitRepository).findById(anyLong());
}
@Test
void testDeleteBDD() {
// given
willThrow(new RuntimeException("throw")).given(visitRepository).delete(any());
// when - none
// then
assertThrows(RuntimeException.class, () -> service.delete(new Visit(1l)));
verify(visitRepository).delete(any());
}
@singun
Copy link
Author

singun commented Apr 8, 2019

mockito 를 사용한 예외 테스트

@singun
Copy link
Author

singun commented Apr 8, 2019

BDDMockito 의 given() 메소드의 인자로 전달되는 mock은 반환 타입을 가지고 있어야 함.
visitorRepository.findById() 의 경우 리턴 타입 있어 given(..).willThrow(..) 로 예외에 대한 테스트가 가능.
visitorRepository.delete() 의 경우 void 로 선언되어 있어 given(..).willThrow(..) 사용 불가능. 순서를 바꾸면 void 타입의 경우에도 예외에 대한 테스트 가능. willThrow(..).given(..).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment