다음 요청을 처리할 수 있는 핸들러 메소드를 맵핑하는 @RequestMapping (또는 @GetMapping, @PostMapping 등)을 정의하세요.
@Controller
public class SampleController {
@GetMapping("/events")
@ResponseBody
public String events(){
return "events";
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void getEvents() throws Exception{
mockMvc.perform(get("/events"))
.andDo(print())
.andExpect(status().isOk());
}
}
@Controller
public class SampleController {
@GetMapping("/events/{id}")
@ResponseBody
public String getEvents(@PathVariable int id){
return "events " + id;
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void getEventsWithId() throws Exception{
mockMvc.perform(get("/events/1"))
.andDo(print())
.andExpect(status().isOk());
mockMvc.perform(get("/events/2"))
.andDo(print())
.andExpect(status().isOk());
mockMvc.perform(get("/events/3"))
.andDo(print())
.andExpect(status().isOk());
}
}
@Controller
public class SampleController {
@PostMapping(
value="/events",
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String createEvent(){
return "event";
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void createEvent() throws Exception{
mockMvc.perform(post("/events")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8))
.andDo(print())
.andExpect(status().isOk());
}
}
@Controller
public class SampleController {
@DeleteMapping("/events/{id}")
@ResponseBody
public String deleteEvents(@PathVariable int id){
return "events " + id;
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void deleteEvents() throws Exception{
mockMvc.perform(delete("/events/1"))
.andDo(print())
.andExpect(status().isOk())
mockMvc.perform(delete("/events/2"))
.andDo(print())
.andExpect(status().isOk());
mockMvc.perform(delete("/events/3"))
.andDo(print())
.andExpect(status().isOk());
}
}
@Controller
public class SampleController {
@PutMapping(
value="/events/{id}",
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String updateEvent(@PathVariable int id){
return "events " + id;
}
}
@RunWith(SpringRunner.class)
@WebMvcTest
public class SampleControllerTest {
@Autowired
MockMvc mockMvc;
@Test
public void updateEvent() throws Exception{
mockMvc.perform(put("/events/1")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8))
.andDo(print())
.andExpect(status().isOk());
mockMvc.perform(put("/events/2")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8))
.andDo(print())
.andExpect(status().isOk());
}
}
참고