작은 지식주머니
Mockito BDD mockito unnecessary stubbings detected 해결 본문
여기까지 온 사람이면 대충 Mockito에 대해서는 알고 있을테니 적당히 작성하도록 하겠습니다.
보통 Unnecessary stubbings detected에 대한 에러는
then 또는 given , when 등에서 사용된 로직이 사용되지 않았을 경우 발생합니다.
첫번째 해결 방법으로는 given 으로 사용하였을떄 그 행위를 선언하고나서 행위를 행하시면 됩니다.
예시코드 )
SignUpForm form = formCustomer(); // Customer를 생성하는 메서드
given(customerInfoRepo.findById(1L)).willReturn((Optional.of(customer)));
CustomerInfoVo newMember = customerInfoService.signUp(form);
만약 3번째 줄이 적혀있지 않았다면 Unnecessary stubbings detected가 발생합니다.
다음은 고의로 Exception을 발생시켰을 경우입니다.
저는 assertThoews 안에 로직을 넣고 해당 에러가 발생하였을 경우 테스트 성공을 선언하려 하였습니다.
하지만 assertThrows를 사용하려 했는데 문제가 하나 발생하였습니다.
asserThrows 안에 Exception.class를 넣었지만 Unnecessary stubbings detected 이 발생한 것입니다.
// when
assertThrows(CustomException.class, () -> {
customerInfoService.signUpCustomerTemp(form);
});
분명 선언을 했지만 Mockito는 인지하지 못하였습니다.
만약 when을 사용하시는 분들이라면 lenient()를 사용하시면 되지만
given을 사용하시는 분들께서는 해당 테스트에 어노테이션 하나를 추가하시면
Unnecessary stubbings detected이 발생하지 않습니다.
@MockitoSettings(strictness = Strictness.LENIENT)
Stub이 조금 더 유연하게 작동합니다.
이상으로 포스팅을 마칠려 합니다.
기본적으로 Unnecessary stubbings detected를 lenient()를 전부 붙여서 넘어가는 것은 별로 탐탁지 않았지만
해당 Throws는 어떻게 하는 방법을 알 수 없어서 사용하게 되었습니다.
'spring' 카테고리의 다른 글
개인 토이 프로젝트 (3) JPA, JWT를 이용한 간단한 RESTful 백엔드 API만들어보기 (0) | 2022.02.21 |
---|---|
개인 토이 프로젝트 (2) JPA, JWT를 이용한 간단한 RESTful 백엔드 API만들어보기 (0) | 2022.02.20 |
개인 토이 프로젝트 (1) JPA, JWT를 이용한 간단한 RESTful 백엔드 API만들어보기 (0) | 2022.02.20 |
SOLID (0) | 2021.11.12 |