test类中进行web虚拟测试

@SpringBootTest 中加入参数webEnvironment 并根据需求设置值

.RANDOM_PORT随机端口号

.DEFINED_PORT默认端口号

.none 不启动web环境

例:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
表示开启web虚拟环境,测试的端口号随机

@AutoConfigureMockMvc   开启虚拟mvc调用

@Autowired MockMvc mockMvc  注入虚拟mvc调用对象

mockMvc.perform()  执行请求

MockMvcRequestBuilders.请求方式(“路径”) 创建虚拟请求

例:

 @Test
    public void test(@Autowired MockMvc mockMvc) throws Exception {
//        创建虚拟请求,访问/books。get方式请求
        RequestBuilder builder = MockMvcRequestBuilders.get("/books");
//        执行请求
        ResultActions perform = mockMvc.perform(builder);
    }

匹配执行状态MockMvcResultMatchers

他有很多种匹配方式比如:

.status()匹配执行状态

.header()匹配响应头

.content()匹配响应体 等等

.status()匹配执行状态StatusResultMatchers

定义本次调用的执行状态预期值

StatusResultMatchers status = MockMvcResultMatchers.status();

Status有很多种预期值

例如

ResultMatcher ok = status.isOk();预计本次调用是成功的

ResultMatcher notFound = status.isNotFound();预计本次调用找不到路径

.header()匹配响应头HeaderResultMatchers

定义本次调用的响应头期值

HeaderResultMatchers header = MockMvcResultMatchers.header();

把期望的key和value放到对应位置

ResultMatcher string = header.string("key","value");

.content()匹配响应体ContentResultMatchers

定义本次调用的响应体期值(json)

ContentResultMatchers content = MockMvcResultMatchers.content();


ResultMatcher books = content.json(“字符串”)

定义本次调用的响应体期值(字符串)

ContentResultMatchers content = MockMvcResultMatchers.content();


ResultMatcher books = content.string(“字符串”)

例:

//      在test中进行web测试
    @Test
    public void testall(@Autowired MockMvc mockMvc) throws Exception {
//        发起虚拟请求
        RequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions perform = mockMvc.perform(builder);
//        测试是否响应成功
        StatusResultMatchers status = MockMvcResultMatchers.status();
        ResultMatcher ok = status.isOk();
        perform.andExpect(ok);
//        测试响应头Content-Type的值是否为application/json
        HeaderResultMatchers header = MockMvcResultMatchers.header();
        ResultMatcher string = header.string("Content-Type", "application/json");
        perform.andExpect(string);
//        测试响应体的数据是否为{"data":[],"code":20041,"msg":"查询成功"}
        ContentResultMatchers content = MockMvcResultMatchers.content();
        ResultMatcher books = content.json("{\"data\":[{\"booksname\":\"三国演义\",\"author\":\"罗贯中\",\"num\":154,\"price\":135,\"id\":1}],\"code\":20041,\"msg\":\"查询成功\"}");
        perform.andExpect(books);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值