All Articles

Test in spring boot

unit test 환경에서는 가능하면 MockitoExtension 을 사용해서 가볍게 실행

@SpringBootTest

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications

@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


@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));
		...
	}
}

Reference

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications

https://stackoverflow.com/questions/61433806/junit-5-with-spring-boot-when-to-use-extendwith-spring-or-mockito