요청 매개변수란?
@RequestParam
@Controller
public class SampleController {
@PostMapping("/events")
@ResponseBody
public Event createEvent(@RequestParam String name){
Event event = new Event();
event.setName(name);
return event;
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void createEvent() throws Exception{
mockMvc.perform(post("/events?name=spring"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(spring));
}
}
혹은 폼 데이터로 보내는 걸 확인하고 싶으면 param을 이용한다.
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void createEvent() throws Exception{
mockMvc.perform(post("/events)
.param("name", "spring"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(spring));
}
}
모든 요청 파라미터를 Map으로 받아올 수도 있다.
@Controller
public class SampleController {
@PostMapping("/events")
@ResponseBody
public Event createEvent(@RequestParam Map<String, String> param){
Event event = new Event();
event.setName(param.get("name"));
return event;
}
}
public class Event {
private Integer id;
private String name;
private Integer limit;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
}
@Controller
public class SampleController {
@PostMapping("/events")
@ResponseBody
public Event createEvent(@RequestParam String name, @RequestParam Integer limit){
Event event = new Event();
event.setName(name);
event.setLimit(limit);
return event;
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void createEvent() throws Exception{
mockMvc.perform(post("/events)
.param("name", "spring")
.param("limit", "20"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(spring));
}
}
참고