controller单元测试

AutoConfigureMockMvc

以上是针对业务层测试,如果想进行接口API测试怎么办呢,难道,开发完成每次调用postman一个个测吗?答案当然是no,不过,你也可以选择一个个测试没什么问题,如果你想通过代码实现模拟http请求就要用到我们的@AutoConfigureMockMvc注解,使用了MockMvc无需启动项目,就可实现接口测试。
以下用到的MockMvc方法介绍

  • mockMvc.perform:执行请求
  • MockMvcRequestBuilders.get:还支持post、put、delete等
  • contentType(MediaType.APPLICATION_JSON_UTF8):表示请求传输的Conent-Type=application/json;charset=utf-8
  • accept(MediaType.APPLICATION_JSON)):客户端希望接收的Conent-Type=application/json;
  • andExpect(MockMvcResultMatchers.status().isOk()):返回响应状态是否为期望的200,如果不是则抛出异常
  • andReturn():返回结果
  1. package com.github.springboot.controller;
  2. import com.github.springboot.domain.User;
  3. import com.google.gson.Gson;
  4. import com.google.gson.GsonBuilder;
  5. import org.junit.jupiter.api.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  9. import org.springframework.boot.test.context.SpringBootTest;
  10. import org.springframework.http.MediaType;
  11. import org.springframework.mock.web.MockHttpServletResponse;
  12. import org.springframework.test.context.junit4.SpringRunner;
  13. import org.springframework.test.web.servlet.MockMvc;
  14. import org.springframework.test.web.servlet.MvcResult;
  15. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  16. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  17. @RunWith(SpringRunner.class)
  18. @SpringBootTest
  19. @AutoConfigureMockMvc
  20. class UserControllerTest {
  21. @Autowired
  22. private MockMvc mockMvc;
  23. @Test
  24. void userAdd() throws Exception{
  25. User user = new User();
  26. user.setName("test");
  27. user.setAge(18);
  28. Gson gson = new GsonBuilder().setPrettyPrinting().create();
  29. MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/user")
  30. .contentType(MediaType.APPLICATION_JSON)
  31. .content(gson.toJson(user))
  32. .accept(MediaType.APPLICATION_JSON))
  33. .andReturn();
  34. MockHttpServletResponse response = mvcResult.getResponse();
  35. System.out.println(response.getStatus());
  36. System.out.println(response.getContentAsString());
  37. }
  38. @Test
  39. void userList() throws Exception{
  40. MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/user/list"))
  41. .andReturn();
  42. MockHttpServletResponse response = mvcResult.getResponse();
  43. System.out.println(response.getStatus());
  44. System.out.println(response.getContentAsString());
  45. }
  46. @Test
  47. void deleteUser() throws Exception{
  48. mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/user/"+1)).andExpect(MockMvcResultMatchers.status().isOk());
  49. }
  50. }