반응형
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();
}
}
반응형
'Spring' 카테고리의 다른 글
[Spring] Intellij에서 WebFlux 시작하기 + 테스트 코드 (0) | 2024.05.10 |
---|---|
[String] mvnw 빌스 시 TEST SKIP하기 (0) | 2021.02.08 |