《SpringBoot篇》14.@AutoConfigureMockMvc测试类实现Web层测试

简介: 《SpringBoot篇》14.@AutoConfigureMockMvc测试类实现Web层测试

1.测试类实现Web层测试


说明:本文是在springboot项目中实现的哦。


(1)在测试类上添加@AutoConfigureMockMvc

@SpringBootTest()
@AutoConfigureMockMvc
class DemoApplicationTests {
    @Test
    void WebFindTest() {
    }
}

(2)在SpringBootTest注解中添加参数webEnvironment

SpringBootTest.WebEnvironment.RANDOM_PORT
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
    @Test
    void testWeb(@Autowired MockMvc mvc) {
    }
}


注:这里WebEnvironment几个参数的含义:


MOCK:根据当前设置确认是否启动web环境,例如使用了Servlet的API就启动web环境,属于适配性的配置

DEFINED_PORT:使用自定义的端口作为web服务器端口

RANDOM_PORT:使用随机端口作为web服务器端口( 建议使用,防止端口冲突)

NONE:不启动web环境

(3)引入MockMvc对象创建访问请求

注:测试可以发现请求成功,测试发送请求可以成功但是无法看到结果,在下一步就可以看到了。

注:web层Controller代码

package com.example.demo.controller;
import com.example.demo.pojo.Admin;
import com.example.demo.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class WebController {
    @GetMapping("findWeb")
    @ResponseBody
    public String finall(){
        return "Web测试成功";
    }
}

注:测试类代码


package com.example.demo;
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.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class DemoApplicationTests {
    //引入MockMvc类型对象
    @Autowired
    private MockMvc mvc;
    @Test
    void WebFindTest() throws Exception {
        //http://localhost:8080/findWeb
        //创建虚拟请求
        //前面的服务器IP地址和端口使用的是当前虚拟的web环境,无需指定,仅指定请求的具体路径即可
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/findWeb");
        //这里需要抛出异常
        mvc.perform(builder);
    }
}

测试成功效果:

image.png


(4)实现请求结果对比

注: 响应对比有四种类型,响应状态匹配、响应体匹配(非json数据格式)、响应体匹配(json数据格式,开发中的主流使用方式)、响应头信息匹配。


a.响应状态匹配

package com.example.demo;
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.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class DemoApplicationTests {
    //引入MockMvc类型对象
    @Autowired
    private MockMvc mvc;
    @Test
    void WebFindTest() throws Exception {
        //http://localhost:8080/findWeb
        //创建虚拟请求
        //前面的服务器IP地址和端口使用的是当前虚拟的web环境,无需指定,仅指定请求的具体路径即可
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/findWeb");
        //这里需要抛出异常
        //获取返回值
    ResultActions perform = mvc.perform(builder);
        //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
        //定义本次调用的预期值
        StatusResultMatchers status = MockMvcResultMatchers.status();
        //预计本次调用时成功的:状态200
        ResultMatcher ok = status.isOk();
        //添加预计值到本次调用过程中进行匹配
        perform.andExpect(ok);
    }
}

b.响应体匹配(非json数据格式)

package com.example.demo;
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.ContentResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class DemoApplicationTests {
    //引入MockMvc类型对象
    @Autowired
    private MockMvc mvc;
    @Test
    void WebFindTest() throws Exception {
        //http://localhost:8080/findWeb
        //创建虚拟请求
        //前面的服务器IP地址和端口使用的是当前虚拟的web环境,无需指定,仅指定请求的具体路径即可
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/findWeb");
        //这里需要抛出异常
        //获取返回值
        ResultActions perform = mvc.perform(builder);
        //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
        //定义本次调用的预期值
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //预计本次调用时成功的:状态200
        ResultMatcher resultMatcher = content.string("Web测试成功");
        //添加预计值到本次调用过程中进行匹配
        perform.andExpect(resultMatcher);
    }
}

测试成功将会访问成功,给大家看一下失败的样式:(会报错)


image.png

c.响应体匹配(json数据格式,开发中的主流使用方式)

Controller类也要改成返回Json


package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebController {
    @GetMapping("findWeb")
    @ResponseBody
    public String finall(){
        return "{\"name\" : Web测试成功}";
    }
}


注意测试类Json写法:


package com.example.demo;
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.ContentResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class DemoApplicationTests {
    //引入MockMvc类型对象
    @Autowired
    private MockMvc mvc;
    @Test
    void WebFindTest() throws Exception {
        //http://localhost:8080/findWeb
        //创建虚拟请求
        //前面的服务器IP地址和端口使用的是当前虚拟的web环境,无需指定,仅指定请求的具体路径即可
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/findWeb");
        //这里需要抛出异常
        //获取返回值
        ResultActions perform = mvc.perform(builder);
        //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
        //定义本次调用的预期值
        ContentResultMatchers content = MockMvcResultMatchers.content();
        //这里注意Json写法格式
        ResultMatcher result = content.json("{\"name\":Web测试成功}");
        //添加预计值到本次调用过程中进行匹配
        perform.andExpect(result);
    }
}

d.响应头信息匹配

package com.example.demo;
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.ContentResultMatchers;
import org.springframework.test.web.servlet.result.HeaderResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class DemoApplicationTests {
    //引入MockMvc类型对象
    @Autowired
    private MockMvc mvc;
    @Test
    void WebFindTest() throws Exception {
        //http://localhost:8080/findWeb
        //创建虚拟请求
        //前面的服务器IP地址和端口使用的是当前虚拟的web环境,无需指定,仅指定请求的具体路径即可
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/findWeb");
        //这里需要抛出异常
        //获取返回值
        ResultActions perform = mvc.perform(builder);
        //响应头
        HeaderResultMatchers header = MockMvcResultMatchers.header();
        ResultMatcher contentType = header.string("Content-Type", "text/plain;charset=UTF-8");
        perform.andExpect(contentType);
    }
}

(4)校验总结

注: 平时都是三种校验一起,(Json与非Json只能一种)


package com.example.demo;
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.ContentResultMatchers;
import org.springframework.test.web.servlet.result.HeaderResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class DemoApplicationTests {
    //引入MockMvc类型对象
    @Autowired
    private MockMvc mvc;
    @Test
    void WebFindTest() throws Exception {
        //http://localhost:8080/findWeb
        //创建虚拟请求
        //前面的服务器IP地址和端口使用的是当前虚拟的web环境,无需指定,仅指定请求的具体路径即可
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/findWeb");
        //这里需要抛出异常
        //获取返回值
        ResultActions perform = mvc.perform(builder);
        //设定预期值 与真实值进行比较,成功测试通过,失败测试失败
        //定义本次调用的预期值
        //响应状态
        StatusResultMatchers status = MockMvcResultMatchers.status();
        ResultMatcher ok = status.isOk();
        perform.andExpect(ok);
        //响应头
        HeaderResultMatchers header = MockMvcResultMatchers.header();
        ResultMatcher contentType = header.string("Content-Type", "text/plain;charset=UTF-8");
        perform.andExpect(contentType);
        //返回的响应体
        ContentResultMatchers content = MockMvcResultMatchers.content();
        ResultMatcher result = content.json("{\"name\":Web测试成功}");
        perform.andExpect(result);
    }
}

2.补充测试层实现数据回滚


说明:使用@Transactional,@Rollback(true)防止执行测试类产生垃圾数据。


package com.example.demo;
import com.example.demo.pojo.Admin;
import com.example.demo.repository.AdminRepository;
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.annotation.Rollback;
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;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@SpringBootTest()
@Transactional
@Rollback
class RollbackTests {
    @Autowired
    private AdminRepository adminRepository;
    @Test
    void WebFindTest()  {
        Admin admin  = new Admin();
        admin.setPassword("123");
        adminRepository.save(admin);
    }
}

3.补充测试用例数据随机


说明: 在配置文件中设置数据为随机,配合@ConfigurationProperties实现随机值注入


test:
  book:
    id: ${random.int}
    id2: ${random.int(10)}
    type: ${random.int!5,10!}
    name: ${random.value}
    uuid: ${random.uuid}
    publishTime: ${random.long}
@Component
@Data
@ConfigurationProperties(prefix = "test.book")
public class BookCase {
    private int id;
    private int id2;
    private int type;
    private String name;
    private String uuid;
    private long publishTime;
}


目录
打赏
0
0
0
0
9
分享
相关文章
Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
35 12
Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
|
5天前
|
AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
23 12
AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
Selenium IDE:Web自动化测试的得力助手
Selenium IDE:Web自动化测试的利器。作为开源工具,Selenium IDE支持录制与回放用户操作,适用于Chrome、Firefox等多浏览器,简化了测试流程,提升了效率,降低了自动化测试的门槛。它还支持导出多种编程语言的脚本,便于测试集成与复用。
150 31
Selenium IDE:Web自动化测试的得力助手
基于SpringBoot+Vue实现的大学生体质测试管理系统设计与实现(系统源码+文档+数据库+部署)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
39 2
Spring Boot 如何测试打包部署
本文介绍了 Spring Boot 项目的开发、调试、打包及投产上线的全流程。主要内容包括: 1. **单元测试**:通过添加 `spring-boot-starter-test` 包,使用 `@RunWith(SpringRunner.class)` 和 `@SpringBootTest` 注解进行测试类开发。 2. **集成测试**:支持热部署,通过添加 `spring-boot-devtools` 实现代码修改后自动重启。 3. **投产上线**:提供两种部署方案,一是打包成 jar 包直接运行,二是打包成 war 包部署到 Tomcat 服务器。
49 10
Selenium:强大的 Web 自动化测试工具
Selenium 是一款强大的 Web 自动化测试工具,包括 Selenium IDE、WebDriver 和 Grid 三大组件,支持多种编程语言和跨平台操作。它能有效提高测试效率,解决跨浏览器兼容性问题,进行性能测试和数据驱动测试,尽管存在学习曲线较陡、不稳定等缺点,但其优势明显,是自动化测试领域的首选工具。
271 17
Selenium:强大的 Web 自动化测试工具
Spring Boot 入门:简化 Java Web 开发的强大工具
Spring Boot 是一个开源的 Java 基础框架,用于创建独立、生产级别的基于Spring框架的应用程序。它旨在简化Spring应用的初始搭建以及开发过程。
107 6
Spring Boot 入门:简化 Java Web 开发的强大工具
springboot之SpringBoot单元测试
本文介绍了Spring和Spring Boot项目的单元测试方法,包括使用`@RunWith(SpringJUnit4ClassRunner.class)`、`@WebAppConfiguration`等注解配置测试环境,利用`MockMvc`进行HTTP请求模拟测试,以及如何结合Spring Security进行安全相关的单元测试。Spring Boot中则推荐使用`@SpringBootTest`注解简化测试配置。
122 4

热门文章

最新文章

  • 1
    打造高效的Web Scraper:Python与Selenium的完美结合
    19
  • 2
    Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
    35
  • 3
    AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
    23
  • 4
    【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
    59
  • 5
    部署使用 CHAT-NEXT-WEB 基于 Deepseek
    412
  • 6
    【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
    31
  • 7
    java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
    45
  • 8
    零基础构建开源项目OpenIM桌面应用和pc web- Electron篇
    31
  • 9
    【01】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-硬件设备实时监控系统运营版发布-本产品基于企业级开源项目Zabbix深度二开-分步骤实现预计10篇合集-自营版
    22
  • 10
    FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
    62
  • AI助理

    你好,我是AI助理

    可以解答问题、推荐解决方案等