프로그래밍 노트/TEST를 해보자
[Mockito] @Spy, @SpyMock 스터빙(stubbing)(thenReturn vs doReturn)
깡냉쓰
2020. 12. 14. 21:23
728x90
반응형
목(Mock)객체를 스터빙(stubbing) 할때 아래와 같이 사용한다.
when(..).thenReturn(..)
List mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("foo");
스파이(Spy)객체도 위와같이 스터빙(stubbing)을 할 것같지만, 위와 같이 사용하면 안된다. 그 이유는 스파이 객체는 리얼 객체이기 때문이다.
스파이(Spy) 객체에서는 when(object)을 사용하면, 실제 객체가 호출되버린다. 따라서 스파이(Spy)객체에서는 when을 사용하지 않고 doReturn(..).when(..)을 사용해야한다.
Sometimes it's impossible or impractical to use when(Object) for stubbing spies. Therefore when using spies please consider doReturn|Answer|Throw() family of methods for stubbing.
List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
https://www.javadoc.io/doc/org.mockito/mockito-core/2.7.17/org/mockito/Mockito.html#spy
728x90
반응형