단위 테스트를 작성하면서 다시는 헷갈리지 않기 위해 영어 문서(Baeldung)을 참고하여 정리하였습니다.
@ExtendWith(MockitoExtention.class)
this is specific to JUnit5, and enables Mockito annotations like @Mock, @InjectMocks, and @Spy in the test class
JUnit5에 관한 어노테이션이며, Mockito 어노테이션을 사용할 수 있게 해 줍니다.
@ExtendWith(MockitoExtension.class)
class ExampleTest {
@InjectMocks
private ExampleService exampleService;
@Mock
ExampleRepository exampleRepository;
@Test
void testExample() {
when(exampleRepository.findById(1))
.thenReturn(Optional.of(new Example(1)));
// ...
}
@Mock
The most widely used annotation in Mockito
we can use @Mock to create and inject mocked instances without having to call Mockito.mock manually
해당 어노테이션을 통해 모킹 된 인스턴스를 주입할 수 있습니다.
@Test
public void whenNotUseMockAnnotation_thenCorrect() {
List mockList = Mockito.mock(ArrayList.class);
mockList.add("one");
Mockito.verify(mockList).add("one");
assertEquals(0, mockList.size());
Mockito.when(mockList.size()).thenReturn(100);
assertEquals(100, mockList.size());
}
===
@Mock
List<String> mockedList;
@Test
public void whenUseMockAnnotation_thenMockIsInjected() {
mockedList.add("one");
Mockito.verify(mockedList).add("one");
assertEquals(0, mockedList.size());
Mockito.when(mockedList.size()).thenReturn(100);
assertEquals(100, mockedList.size());
}
@Spy
annotation to spy on an existing instance.
(기존 인스턴스인 척하게 하는 스파이 객체를 만들어줍니다.)
@Spy
List<String> spiedList = new ArrayList<String>();
@Test
public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
spiedList.add("one");
spiedList.add("two");
Mockito.verify(spiedList).add("one");
Mockito.verify(spiedList).add("two");
assertEquals(2, spiedList.size()); //** use real method
Mockito.doReturn(100).when(spiedList).size();
assertEquals(100, spiedList.size());
}
- Used the real method spiedList.add() to add elements to the spiedList.
- Stubbed the method spiedList.size() to return 100 instead of 2 using Mockito.doReturn().
- Mockito.doReturn을 통해 메서드를 스텁 할 수 있습니다.
@Captor
annotation to create an ArgumentCaptor instance.
@Test
public void whenNotUseCaptorAnnotation_thenCorrect() {
List mockList = Mockito.mock(List.class);
ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
mockList.add("one");
Mockito.verify(mockList).add(arg.capture());
assertEquals("one", arg.getValue());
}
===
@Mock
List mockedList;
@Captor
ArgumentCaptor argCaptor;
@Test
public void whenUseCaptorAnnotation_thenTheSame() {
mockedList.add("one");
Mockito.verify(mockedList).add(argCaptor.capture());
assertEquals("one", argCaptor.getValue());
}
@Captor for the same purpose, to create an ArgumentCaptor instance.
@InjectMocks
annotation to inject mock fields into the tested object automactically.
테스트 객체에 자동으로 mock 필드를 주입해 주는 어노테이션입니다.
https://www.baeldung.com/mockito-annotations