- 新建spring boot项目
- 添加REST接口测试
- 编写单元测试
- spring boot 热启动
新建spring boot项目
- 新建一个Module
- 选择spring boot initializr,然后Next
- 设置项这里,只需要修改一下Artifact即可,会对应生成Name
- 按需选择依赖项,这里选择web
- 创建成功后,pom.xml如下,自动引入里刚才选择的web依赖项,还添加了test依赖
- 创建成功后的工程目录结构如下:
添加REST接口测试
启动spring boot Application类,控制台输出如下,表示启动成功
注意:如果端口被占用,则需要在application.properties中配置端口,我这里配置了8090
浏览器输入localhost:8090/test/hello,页面返回“my first spring boot project”,说明REST接口测试通过
一定要
否则会找不到url,页面提示如下:
编写单元测试
创建spring boot工程时,自动生成了一个测试类,现在用这个测试类测试。
测试结果如下,status = 200(状态码200),body = my first spring boot project(返回体,是输出的内容),表示测试成功
测试案例中用到了MockMvc,@Runwith
MockMvc:基于RESTful风格的SpringMvc测试
对于前后端分离的项目而言,无法直接从前端静态代码中测试接口的正确性,因此可以通过MockMVC来模拟HTTP请求。基于RESTful风格的SpringMVC的测试,我们可以测试完整的Spring MVC流程,即从URL请求到控制器处理,再到视图渲染都可以测试。
作用是无需启动服务器,利用Mock API模拟测试,它的执行过程如下:
- perform执行一个请求
- get构造一个GET请求(这里可以是PUT、POST、DELETE、、、)
- accept接受的数据格式
- andExcept添加执行后的断言
- andDo添加结果处理器,例如print结果
- andReturn执行完毕返回结果
@Ruwith 是一个测试启动器,它需要的依赖项是Junit
spring boot 热启动
在调试接口时,需要对代码进行修改,修改完后要重启Web应用,此时spring boot的热启动就突出它的优势。它可以在代码修改后,实时生效,而不用重启web应用。使用热启动需要在pom.xml中引入spring-boot-devtolls,然后设置Optional为true,这个依赖项在创建工程时,可以选择