SpringBoot中使用MockMvc测试

来源:互联网 发布:java cellstyle 编辑:程序博客网 时间:2024/06/13 06:45

需求

需要在测试类里实现,模拟接口访问。用到MockMvc

实现

测试类里添加一下代码

    private MockMvc mvc;      @Before      public void setUp() throws Exception {          mvc = MockMvcBuilders.standaloneSetup(controller).build();      }  
    @Test      public void getGitHubEntityByUsername() throws Exception {          MvcResult result = mvc.perform(                  MockMvcRequestBuilders.get("/github/get/users/Datartisan")                          .accept(MediaType.APPLICATION_JSON))                          .andReturn();          int statusCode = result.getResponse().getStatus();          Assert.assertEquals(statusCode, 200);          String body = result.getResponse().getContentAsString();          System.out.println("body:"+body);      }  

更多参数资料