unit test 환경에서는 가능하면 MockitoExtension 을 사용해서 가볍게 실행
@SpringBootTest
@ExtendWith(SpringExtension.class) 와 동일하다고 공식 문서에 나와 있음, SpringExtension을 가지고 테스트가 확장됨
기본적으로는 서버를 실행시키지 않지만 webEnvironment 속성을 줘서 변경 가능함
SpringExtension
integrates the Spring TestContext Framework into JUnit 5’s Jupiter programming model.
Annotation that can be specified on a test class that runs Spring Boot based tests.
Spring TestContext Framework
- Uses SpringBootContextLoader as the default ContextLoader when no specific @ContextConfiguration(loader=…) is defined.
- Automatically searches for a @SpringBootConfiguration when nested
@Configuration
is not used, and no explicit classes are specified. - Allows custom Environment properties to be defined using the properties attribute.
- Allows application arguments to be defined using the args attribute.
- Provides support for different webEnvironment modes, including the ability to start a fully running web server listening on a defined or random port.
@ExtendWith(MockitoExtension.class)
Developers can register one or more extensions declaratively by annotating a test interface, test class, test method, or custom composed annotation with @ExtendWith(…)
and supplying class references for the extensions to register.
Extension that initializes mocks and handles strict stubbings. This extension is the JUnit Jupiter equivalent of our JUnit4 MockitoJUnitRunner
Unit Test Example
@Mock
mock injection + void method
@ExtendWith(MockitoExtension.class)
@DisplayName("EventService Test")
public class EventServiceTest {
@Mock
EventRepository eventRepository;
@Test
void set_event_success() {
...
doNothing().when(eventRepository).enqueueEvent(event);
...
}
}
mock injection + T method
@ExtendWith(MockitoExtension.class)
@DisplayName("EventService Test")
public class EventServiceTest {
@Mock
EventRepository eventRepository;
@Test
void set_event_success() {
...
when(eventRepository.getEvents()).thenReturn(List.of(EventVo));
...
}
}