How to write test code in springboot

In springboot, running 'controller test' instead of unit test is typical. Springboot has its own testing features with 'MockMvc'. 

The default annotation for test is @SpringBootTest. You can use @AutoConfigureMockMvc with it to create MockMvc and run test. Or for simple test which does not require service or repository layer, you can simply use @WebMvcTest solely.


Three substantial MockMvc methods that are used for testings are like below

1. perform(): runs the controller as if the application got a HTTP request. Receives 'RequestBuilder' as an input and returns 'ResultActions' as an output. ResultActions carries not only the response of the request, but the steps application went through.

2. andExpect(): check if the ResultActions is adequate using its parameter 'ResultMatcher'.

3. andDo(): can implement additional tasks on the ResultActions using its parameter 'ResultHandler'.


Thus, the code would like the below example.


@SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc // 컨트롤러 뿐만아니라 @Repository, @Service까지 메모리에 다 올린다. public class BoardControllerTest { @Autowired private MockMvc mockMvc; @Test public void testHello() throws Exception { mockMvc.perform(get("/hello").param("name", "sky")) .andExpect(status().isOk()) .andExpect(content().string("Hello : sky")) .andDo(print()); } }



댓글

이 블로그의 인기 게시물

Interface of Java

Data Analytics Overview(OLTP vs OLAP)

Leetcode