网站建设建网站年轻的母亲,通信建设网站,百度推广系统营销平台,辽宁网站建设学校上文 java springboot测试类虚拟MVC环境 匹配返回值与预期内容是否相同 (JSON数据格式) 版 中 我们展示 json匹配内容的方式 那么 本文我们来看看Content-Type属性的匹配方式
首先 我们从返回体可以看出 Content-Type 在请求头信息 Headers 中 我们直接将测试类代码更改如下 …上文 java springboot测试类虚拟MVC环境 匹配返回值与预期内容是否相同 (JSON数据格式) 版 中 我们展示 json匹配内容的方式 那么 本文我们来看看Content-Type属性的匹配方式
首先 我们从返回体可以看出 Content-Type 在请求头信息 Headers 中 我们直接将测试类代码更改如下
package com.example.webdom;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.HeaderResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;SpringBootTest(webEnvironment SpringBootTest.WebEnvironment.RANDOM_PORT)
AutoConfigureMockMvc
public class WebDomApplicationTests {Testvoid contextLoads(Autowired MockMvc mvc) throws Exception {MockHttpServletRequestBuilder builder MockMvcRequestBuilders.get(/TextWeb);ResultActions action mvc.perform(builder);HeaderResultMatchers header MockMvcResultMatchers.header();ResultMatcher contentType header.string(Content-Type,application/json);action.andExpect(contentType);}
}这里 我们改成 匹配他的 header 所以 MockMvcResultMatchers 要调 header 然后 我们要查看请求头的哪个值 这个我们要告诉他 我们要查 的键叫 Content-Type 我们的预期值是 application/json 最后进行匹配
这里 我们尝试运行函数 我们返回的就是个json 这个明显是会运行成功的 这边 我们直接改成 接口返回 String 字符串 然后 我们再次运行测试类 这边就报错了 这边的信息依旧这么给力 他告诉我们 预期值是 application/json 实际值是 text/plain;charsetUTF-8