스프링 프레임 워크에서 지원
@PostMapping("/user")
public @ResponseBody User create(@RequestBody User user) {
return null;
}
content-type에 따라 컨버팅 한다.
@RestController
가 붙어 있으면 @ResponseBody
는 생략이 가능하다.@Controller
일 경우 뷰네임 리졸버를 쓰기 때문에 뷰를 찾으려 함import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void hello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("hello"));
}
@Test
public void createUser_JSON() throws Exception {
String userJson = "{\\"username\\":\\"cmlee\\", \\"password\\":\\"123\\"}";
mockMvc.perform(post("/users/create")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(userJson))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username",
is(equalTo("cmlee"))))
.andExpect(jsonPath("$.password",
is(equalTo("123"))));
}
}
@RestController
public class UserController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@PostMapping("/users/create")
public User create(@RequestBody User user) {
return user;
}
}