1、测试案例
@AutoConfigureMockMvc@RunWith(SpringRunner.class)@SpringBootTest(classes = {MockmvcBootApplication.class})class MockmvcBootApplicationTests { private static final Logger LOGGER = LoggerFactory.getLogger(MockmvcBootApplicationTests.class); @Autowired private MockMvc mockMvc; @Test public void testGet() { try { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(new URI("/api/testGet/1")) .param("param1","yyy"); MvcResult mvcResult = mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); int status = mvcResult.getResponse().getStatus(); LOGGER.info("status = {}",status); } catch (URISyntaxException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Test public void testGet2() { try { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.request(HttpMethod.GET, new URI("/api/testGet2")) ; MvcResult mvcResult = mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); int status = mvcResult.getResponse().getStatus(); LOGGER.info("status = {}",status); } catch (URISyntaxException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Test public void testPost(){ MockHttpServletRequestBuilder request = null; try { request = MockMvcRequestBuilders.request(HttpMethod.POST, new URI("/api/testPost"))
2、测试接口
@RequestMapping(value = {"/api"})@RestControllerpublic class TestController { private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); @GetMapping(value = "/testGet/{ye}") public String getTest(@RequestParam(value = "param1")String param1,@PathVariable(value = "ye")String ye){ return ye + "你好,rrr" + param1; } @GetMapping(value = "/testGet2") public String getTest2(){ return "你好,ttt"; } @PostMapping(value = "/testPost") public String getPost(@RequestBody User user){ LOGGER.info("{}",user); return "哈哈"; }}
3、实体类
public class User { private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User() { } public User(Integer id, String username, String password) { this.id = id; this.username = username; this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; }}