MockMvc를 SpringBootTest와 함께 사용하는 것과 WebMvcTest를 사용하는 것의 차이점
저는 Spring Boot를 처음 사용했으며 SpringBoot에서 테스트가 어떻게 작동하는지 이해하려고합니다. 다음 두 코드 스 니펫의 차이점이 무엇인지 약간 혼란 스럽습니다.
코드 스 니펫 1 :
@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerApplicationTest {
@Autowired
private MockMvc mvc;
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}
이 테스트는 기능 슬라이스 테스트 용이라고 생각하는 @WebMvcTest 주석을 사용하고 웹 애플리케이션의 Mvc 레이어 만 테스트합니다.
코드 조각 2 :
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}
이 테스트는 @SpringBootTest 주석과 MockMvc를 사용합니다. 그렇다면 이것이 코드 조각 1과 어떻게 다른가요? 이것이 다른 점은 무엇입니까?
편집 : 코드 조각 3 추가 (Spring 문서에서 통합 테스트의 예로 찾았습니다)
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/");
}
@Test
public void getHello() throws Exception {
ResponseEntity<String> response = template.getForEntity(base.toString(),
String.class);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}
@SpringBootTest is the general test annotation. If you're looking for something that does the same thing prior to 1.4, that's the one you should use. It does not use slicing at all which means it'll start your full application context and not customize component scanning at all.
@WebMvcTest is only going to scan the controller you've defined and the MVC infrastructure. That's it. So if your controller has some dependency to other beans from your service layer, the test won't start until you either load that config yourself or provide a mock for it. This is much faster as we only load a tiny portion of your app. This annotation uses slicing.
Reading the doc should probably help you as well.
@SpringBootTest annotation tells Spring Boot to go and look for a main configuration class (one with @SpringBootApplication for instance), and use that to start a Spring application context. SpringBootTest loads complete application and injects all the beans which can be slow.
@WebMvcTest - for testing the controller layer and you need to provide remaining dependencies required using Mock Objects.
Few more annotations below for your reference.
Testing slices of the application Sometimes you would like to test a simple “slice” of the application instead of auto-configuring the whole application. Spring Boot 1.4 introduces 4 new test annotations:
@WebMvcTest - for testing the controller layer
@JsonTest - for testing the JSON marshalling and unmarshalling
@DataJpaTest - for testing the repository layer
@RestClientTests - for testing REST clients
Refer for more information : https://spring.io/guides/gs/testing-web/
MVC tests are intended to cover just the controller piece of your application. HTTP requests and responses are mocked so the real connections are not created. On the other hand, when you use @SpringBootTest, all the configuration for the web application context is loaded and the connections are going through the real web server. In that case, you don’t use the MockMvc bean but a standard RestTemplate instead (or the new alternative TestRestTemplate).
So, when should we choose one or the other? @WebMvcTest is intended to test unitarily the controller from the server side. @SpringBootTest, on the other hand, should be used for integration tests, when you want to interact with the application from the client side.
That doesn’t mean that you can’t use mocks with @SpringBootTest; if you’re writing an integration test, that could still be necessary. In any case, it’s better not to use it just for a simple controller’s unit test.
source - Learning Microservices with Spring Boot
'Program Club' 카테고리의 다른 글
| List vs ArrayList vs Dictionary vs Hashtable vs Stack vs Queue? (0) | 2020.11.27 |
|---|---|
| Pandas 데이터 프레임을 시리즈로 변환 (0) | 2020.11.27 |
| Java 스트림 toArray ()는 특정 유형의 배열로 변환 (0) | 2020.11.27 |
| React JS index.js 파일이 id 참조를 위해 index.html에 연결하는 방법은 무엇입니까? (0) | 2020.11.27 |
| React Router를 사용하여 페이지를 리디렉션하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.27 |