Spring
[Spring JUnit] SpringBoot에서 Controller 테스트를 위한 JUnit 구조
MOMOBOB
2021. 1. 13. 22:59
반응형
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
@AutoConfigureMockMvc
@SpringBootTest
class ControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
public ObjectMapper objectMapper;
@Autowired
public WebApplicationContext context;
public HttpHeaders headers;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(new CharacterEncodingFilter("UTF-8", true))
.alwaysDo(print()).build();
this.headers = new HttpHeaders();
}
@Test
void testFindAll() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("", "");
String requestJsonString = objectMapper.writeValueAsString(params);
MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/api/path")
.headers(headers)
.content(requestJsonString)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andReturn();
}
}
반응형