개발/Spring
[Mockito Test] doNothing 에러 (Only void methods can doNothing())
쩨이엠
2024. 4. 17. 22:14
728x90
반응형
Mockito로 Unit Test를 하는 도중 Service 내에서 다른 API 호출건이 포함되어있다
테스트할 때에는 포인트 적립이 되지 않도록 Mocking을 하기 위해 doNothing을 사용했다
Mockito.doNothing().when(pointApi).savePoint(any());
그리고 다음과 같은 에러를 받았다
Only void methods can doNothing()!
Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
org.mockito.exceptions.base.MockitoException:
Only void methods can doNothing()!
Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
doNothing이란 메소드는 void인 경우에만 사용할 수 있다는 말이었는데
그렇다면 받아올 것에는 무엇을 써야하나
하고 찾은 것이 doReturn
@SpyBean
private PointApi pointApi;
@Test
void test() {
..
// when
Mockito.doReturn(null).when(pointApi).savePoint(any());
..
}
void가 아닌 경우에는 SpyBean으로 Mocking한 후, Return값을 설정해줘서 동일하게 API가 호출된 것처럼 할 수 있다
나는 적립이 안되도록만 하면 되기때문에 null로 리턴받기 성공 !
728x90
반응형