栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 中mockMVC测试

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 中mockMVC测试

SpringBoot 中mockMVC测试
  • mockMVC可实现在非启动状态下测试Controller类
package cn.tedu.boot.demo.controller;

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.http.MediaType;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;


@SpringBootTest
@AutoConfigureMockMvc   //自动配置MockMvc
public class AdminControllerTests {
    @Autowired
    MockMvc mockMvc;  //Mock: 模拟

    @Sql("classpath:truncate.sql")
    @Sql("classpath:insert.sql")
    @Test
    public void testLoginSuccessfully() throws Exception{
        // 准备测试数据, 不需要封装
        String username = "test001";
        String password = "123456";
        // 请求路径,不需要写协议、服务器主机端口号
        String url = "/admins/login";
        mockMvc.perform(
                MockMvcRequestBuilders.post(url)  // 根据请求方式决定调用的方法
            	// 请求数据的文档类型, 例如:application/json; charset=utf-8
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)  
            	// 请求参数,有多个时,多次调用param()方法
                .param("username",username)  
                .param("password",password)
           	 	// 接受的响应结果的文档类型,注意:perform()方法到此结束
                .accept(MediaType.APPLICATION_JSON)) 
            	// 预判结果,类似断言
                .andExpect( 
                        MockMvcResultMatchers
                        .jsonPath("state") //预判响应的JSON结果中将会有名为state的属性
            			//预判响应的JSON结果中名为state的属性的值,注意: andException()方法到此结束
                        .value(200)) 
                .andDo( // 需要执行某任务
                        MockMvcResultHandlers.print()); // 打印日志

    }
}

在执行以上代码时,响应的JSON中如果包含中文,可能会出现乱码,需要在配置文件(application.properties或application.yml中配置)中添加配置。

在.properties文件中:

server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8

在.yml文件中:

server:
  servlet:
    encoding:
      force: true
      charset: utf-8
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/959321.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号