温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-12-04 16:42:41 来源:亿速云 阅读:198 作者:Leah 栏目:编程语言

在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进行单元测试的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI