在SpringBoot中怎么对restfulapi进行单元测试

在SpringBoot中怎么对restful api进行单元测试?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联,专注为中小企业提供官网建设、营销型网站制作、响应式网站开发、展示型成都网站建设、网站设计等服务,帮助中小企业通过网站体现价值、有效益。帮助企业快速建站、解决网站建设与网站营销推广问题。

1.添加Springboot测试注解

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
}

2.伪造mvc环境

 // 注入Spring 工厂
  @Autowired
  private WebApplicationContext wac;
 //伪造mvc环境
  private MockMvc mockMvc;
  @Before
  public void setup(){
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }

3.引入静态方法

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

3.编写测试方法

@Test
  public void whenXXXXSuccess() throws Exception {
    //模拟发送请求
    String result =
    mockMvc.perform(get("/user") //发往/user的get请求,可以换成post,put,delete方法执行相应请求
            .param("username","xxx") //get请求时填写参数的位置
            .contentType(MediaType.APPLICATION_JSON_UTF8) //utf编码
            .content(content)) //post和put请求填写参数的位置
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.length()").value(3)) //期望的json返回结果
        .andReturn().getResponse().getContentAsString(); //对返回字符串的json内容进行判断
    log.info(result);
  }

看完上述内容,你们掌握在SpringBoot中怎么对restful api进行单元测试的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


名称栏目:在SpringBoot中怎么对restfulapi进行单元测试
分享链接:http://scyanting.com/article/pgpjsc.html