상세 컨텐츠

본문 제목

Test

스프링

by e7e 2022. 6. 8. 08:29

본문

pom.xml에 아래 내용 추가

		<!-- Junit5 다른 것도 끌어옴 -->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<version>5.8.2</version>
			<scope>test</scope>
		</dependency>

		<!-- Junit 안에서 사용되는 Matcher 라이브러리 없으면 MockMvc 사용시 에러 -->
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest</artifactId>
			<version>2.2</version>
			<scope>test</scope>
		</dependency>

		<!-- jsonPath사용에 에러 발생시 버젼호환성 문제일 가능성이 높음 -->
		<dependency>
			<groupId>com.jayway.jsonpath</groupId>
			<artifactId>json-path</artifactId>
			<version>2.7.0</version>
		</dependency>
        
		<!-- Junit을 편하게 사용할 수 있도록 해주는 스프링 라이브러리 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.2.19.RELEASE</version>
			<scope>test</scope>
		</dependency>

사용(처음 볼 땐 낯설지만, 그냥 매번 붙여쓰게 됨)

//Junit5 사용
@ExtendWith(SpringExtension.class)

//Context설정파일 지정 classpath를 사용해도 됨
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml")

//web구성 MockMvc사용시 필요, Mapper나 Service를 테스트 할 땐 굳이 필요없음
@WebAppConfiguration

 

@BeforeAll // static으로 전체 시작전 1번만
@AfterAll   // static으로 전체 끝나고 1번만

@BeforeEach // @Test 전에 매번
@AfterEach // @Test 후에 매번

@Test    // Test

@DisplayName("테스트명")  // 없어도 됨

@Disabled            // 비활성화

 

 

MockMvc의 한계

MockMvc provides an elegant and easy-to-use API to call web endpoints and to inspect and assert their response at the same time. 
Despite all its benefits, it has a few limitations.

First of all, it does use a subclass of the DispatcherServlet to handle test requests. 
To be more specific, the TestDispatcherServlet is responsible for calling controllers and performing all the familiar Spring magic.

The MockMvc class wraps this TestDispatcherServlet internally. 
So every time we send a request using the perform() method, MockMvc will use the underlying TestDispatcherServlet directly. 
Therefore, there are no real network connections made, and consequently, 
we won't test the whole network stack while using MockMvc.

Also, because Spring prepares a fake web application context to mock the HTTP requests and responses, 
it may not support all the features of a full-blown Spring application.

For example, this mock setup doesn't support HTTP redirections. 
This may not seem that significant at first. 
However, Spring Boot handles some errors by redirecting the current request to the /error endpoint. 
So if we're using the MockMvc, we may not be able to test some API failures.

As an alternative to MockMvc, 
we can set up a more real application context and then use RestTemplate, 
or even REST-assured, to test our application.

'스프링' 카테고리의 다른 글

log4j2  (0) 2022.06.28
MyBatipse  (0) 2022.06.10
rest client  (0) 2022.05.31
hidden method filter  (0) 2022.05.25
Security AJAX  (2) 2022.05.23

관련글 더보기