欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MockMvc 单元测试

程序员文章站 2022-04-30 09:43:28
...

 MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,这样可以使得测试速度快、不依赖网络环境,而且提供了一套验证的工具,这样可以使得请求的验证统一而且很方便。
 MockMvcBuilder是用来构造MockMvc的构造器,其主要有两个实现:StandaloneMockMvcBuilder和DefaultMockMvcBuilder,分别对应两种测试方式,即独立安装和集成Web环境测试(此种方式并不会集成真正的web环境,而是通过相应的Mock API进行模拟测试,无须启动服务器)。对于我们来说直接使用静态工厂MockMvcBuilders创建即可。

@RunWith(SpringRunner.class)
@SpringBootTest()
public class test {
    @Autowired
    private WebApplicationContext wac; // 注入WebApplicationContext
    private MockMvc mockMvc; // 模拟MVC对象。

    @Before // 在测试开始前初始化工作
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void test() throws Exception {
        String responseString = mockMvc.perform(get("/test") //调用接口
                .contentType(MediaType.APPLICATION_JSON_UTF8)  //指定请求的contentType头信息
                .param("name", "测试")  ////请求参数
                .param("phone", "18758694528")
                .accept(MediaType.APPLICATION_JSON))  //接收的类型
                .andExpect(status().isOk())   //判断接收到的状态是否200
                .andDo(print())         //打印出请求和相应的内容
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) //匹配返回值中的内容
                .andReturn().getResponse().getContentAsString();//将相应的数据转换为字符串

        System.out.println(responseString);
    }
}

如果项目中使用了shiro框架。有可能报错:org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code

则需要添加以下内容:

private ThreadState _threadState;
protected Subject _mockSubject;

@Before
public void before() {
    _mockSubject = Mockito.mock(Subject.class);
    _threadState = new SubjectThreadState(_mockSubject);
    _threadState.bind();
}