测试前关闭web项目。springboot启动程序WebApplication.class

笔者本地自定了端口SpringBootTest.WebEnvironment.DEFINED_PORT

代码如下:

import com.xxx.web.WebApplication;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import java.time.Instant;
import java.util.Random; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@AutoConfigureMockMvc
public class TestAppController { @Autowired
private WebApplicationContext context; @Autowired
private MockMvc mvc; private MockHttpSession session;// 1.定义一个变量保存session String pathOnClasspath; @Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
session = new MockHttpSession(); //2.初始化
} @Test
public void login() throws Exception {
// 登陆
MockHttpServletRequestBuilder loginRequestBuilder = MockMvcRequestBuilders.post("/user2/login")
.param("loginName", "test")
.param("password", "567")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON)
.session(session);//3.当某个请求需要session时,直接在构造器中绑定需要的session
mvc.perform(loginRequestBuilder).andDo(MockMvcResultHandlers.print()); } @Test
public void save() throws Exception { //先登录
login(); mvc.perform(post("/app/save")
.param("name","测试")
.param("categoryId","567")
.param("description","休闲益智类游戏语音识别测试")
.session(session)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
//.andExpect(jsonPath("$",hasSize(1)))
//.andExpect(jsonPath("$.message").value(is("保存成功")))
//.andExpect(jsonPath("$.message"),is("保存成功"))
.andDo(MockMvcResultHandlers.print());
} @Test
public void update() throws Exception{
Random rnd = new Random();
int id = rnd.nextInt(6);
mvc.perform(
post("/app/update")
.param("id", String.valueOf(id))
.param("name", String.format("测试%s", Instant.now().toEpochMilli()))
.param("description", "描述12121")
).andDo(MockMvcResultHandlers.print());
} @Test
public void list() throws Exception {
mvc.perform(get("/app/list")
.contentType(MediaType.TEXT_HTML))
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print());
} @Test
public void filteredList() throws Exception {
mvc.perform(post("/app/list")
.param("keyword","111")
.contentType(MediaType.TEXT_HTML))
.andExpect(status().isOk())
.andDo(MockMvcResultHandlers.print());
} @Test
public void testisDuplicatedName() throws Exception
{
mvc.perform(post("/app/isDuplicatedName")
.param("name","测试")
).andDo(MockMvcResultHandlers.print());
} }

测试输出效果

其他参考:

https://www.petrikainulainen.net/programming/spring-framework/integration-testing-of-spring-mvc-applications-write-clean-assertions-with-jsonpath/

使用MockMvc进行springboot调试(SpringbootTest)的更多相关文章

  1. SpringBoot基础之MockMvc单元测试

    SpringBoot创建的Maven项目中,会默认添加spring-boot-starter-test依赖.在<5分钟快速上手SpringBoot>中编写的单元测试使用了MockMvc.本 ...

  2. SpringBoot配置文件(1)

    配置文件 1.配置文件 SpringBoot使用一个全局的配置文件 application.properties application.yml 配置文件名是固定的: 他的作用是修改SpringBoo ...

  3. SpringBoot详解

    1.Hello,World! 1.1.SpringBoot简介 回顾什么是Spring Spring是一个开源框架,2003 年兴起的一个轻量级的Java 开发框架,作者:Rod Johnson . ...

  4. SpringBoot Maven项目 Helloworld 测试

    SpringBoot 化繁为简,简化配置 SpringBoot官方:http://projects.spring.io/spring-boot/SpringBoot使用介绍:http://blog.c ...

  5. [02-01]Java学习路线(完整详细版)

    Java基础课程 Java基础课程内容涉及:Java开发介绍.Java数组.Java面向对象.常用基础类.集合.IO流.多线程.异常.网络.反射. 第一阶段:Java基础 1 第一部分:Java开发介 ...

  6. SpringBoot------MockMvc单元测试

    1.添加测试依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. ...

  7. 单元测试 - SpringBoot2+Mockito实战

    单元测试 - SpringBoot2+Mockito实战 在真实的开发中,我们通常是使用SpringBoot的,目前SpringBoot是v2.4.x的版本(SpringBoot 2.2.2.RELE ...

  8. SpringBoot------单元测试

    1.添加测试依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId&g ...

  9. 分布式任务调度平台XXL-JOB学习笔记一

    分布式任务调度平台XXL-JOB学习笔记一 XXL-JOB是一个轻量级分布式任务调度平台,其核心设计目标是开发迅速.学习简单.轻量级.易扩展.现已开放源代码并接入多家公司线上产品线,开箱即用.码云地址 ...

随机推荐

  1. 《The one!》团队作业五:团队项目需求改进与系统设计

    项目 内容 作业所属课程 所属课程 作业要求 作业要求 团队名称 < The One !> 作业学习目标 (1)掌握面向对象需求分析方法:(2)学习软件系统总体结构和数据库逻辑结构设计,学 ...

  2. c#压缩和解压缩

    C# 文件/文件夹压缩解压缩   项目上用到的,随手做个记录,哈哈. 直接上代码: 1 using System; 2 using System.Data; 3 using System.Config ...

  3. 删除TOMCAT服务器上的文件

    deleteFile(文件名称,路径名称); public boolean deleteFile(String filename,String filepath){  String path =Ser ...

  4. python - django (查询、聚合、分组)

    # """ ---- 正向查询按字段,反向查询按表名 一: 一对多 正向查询:(字段对象.关联表.查询字段) x_obj = models.Book.objects.fi ...

  5. Mac OS终端利器iTerm2(完美替代bash)

    iTerm2 iTerm一个为Mac OS X编写的,功能齐全的终端仿真程序:目标是在为用户提供OS X下最佳的命令行体验,iTerm 2有很多能够提升效率的实用功能.比如说窗口分割.热键窗口.智能搜 ...

  6. 解决appium自带的Chromedriver版本和设备Android System Webview版本不一致的问题

    报错信息 selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred w ...

  7. [GraphQL] Reuse GraphQL Selection Sets with Fragments

    Fragments are selection sets that can be used across multiple queries. They allow you to refactor re ...

  8. git合并之 merge和rebase

    合并有两种方法: git rebase 和git merge 优先用 rebase!!!! 区别: 1. 使用git merge git checkout dev git merge master 或 ...

  9. 2019年京东 PHP工程师面试题

    1. Apache与Nginx大访问下性能描述正确的是? A.Apache所采用的epoll网络I/O模型非常高效B.Nginx使用了最新的kqueue和select网络I/O模型C.Apache进程 ...

  10. MongoDB 查看存储引擎

    需要登录到具体的主/从节点查询,mongos查询不到 db.serverStatus() 其中有这个 "storageEngine" : {  "name" : ...