폼을 보여줄 요청 처리
@Controller
public class SampleController {
@GetMapping("/events/form")
public String eventsForm(Model model) {
Event newEvent = new Event();
newEvent.setLimit(50);
model.addAttribute("event", newEvent);
return "events/form";
}
@PostMapping("/events")
@ResponseBody
public Event createEvent(@RequestParam String name, @RequestParam Integer limit){
Event event = new Event();
event.setName(name);
event.setLimit(limit);
return event;
}
}
HTMl 뷰로도 테스트할 수 있고 포스트맨을 사용해 테스트할 수도 있다.
뷰 생성
타임리프
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Create New Event</title>
</head>
<body>
<form action="#" th:action="@{/events}" method="post" th:object="${event}">
<input type="text" title="name" th:field="*{name}"/>
<input type="text" title="limit" th:field="*{limit}"/>
<input type="submit" value="Create"/>
</form>
</body>
</html>
테스트 코드
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void eventForm() throws Exception{
mockMvc.perform(get("/events/form"))
.andDo(print())
.andExpect(view().name("/events/form"))
.andExpect(model().attributeExists("event"));
}
@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));
}
}
참고