• 新建spring boot项目
  • 添加REST接口测试
  • 编写单元测试
  • spring boot 热启动

新建spring boot项目

  1. 新建一个Module


springboot新建modules springboot新建接口_springboot新建modules


  1. 选择spring boot initializr,然后Next


springboot新建modules springboot新建接口_springboot新建modules_02


  1. 设置项这里,只需要修改一下Artifact即可,会对应生成Name


springboot新建modules springboot新建接口_springboot新建modules_03


  1. 按需选择依赖项,这里选择web


springboot新建modules springboot新建接口_springboot新建modules_04


  1. 创建成功后,pom.xml如下,自动引入里刚才选择的web依赖项,还添加了test依赖


springboot新建modules springboot新建接口_springboot新建modules_05


  1. 创建成功后的工程目录结构如下:


springboot新建modules springboot新建接口_springboot新建modules_06



添加REST接口测试


springboot新建modules springboot新建接口_springboot新建modules_07


启动spring boot Application类,控制台输出如下,表示启动成功


springboot新建modules springboot新建接口_springboot新建modules_08


注意:如果端口被占用,则需要在application.properties中配置端口,我这里配置了8090

浏览器输入localhost:8090/test/hello,页面返回“my first spring boot project”,说明REST接口测试通过


springboot新建modules springboot新建接口_springboot新建modules_09


一定要


springboot新建modules springboot新建接口_springboot新建modules_10


否则会找不到url,页面提示如下:


springboot新建modules springboot新建接口_springboot新建modules_11



编写单元测试

创建spring boot工程时,自动生成了一个测试类,现在用这个测试类测试。


springboot新建modules springboot新建接口_springboot新建modules_12


测试结果如下,status = 200(状态码200),body = my first spring boot project(返回体,是输出的内容),表示测试成功


springboot新建modules springboot新建接口_springboot新建modules_13


测试案例中用到了MockMvc,@Runwith

MockMvc:基于RESTful风格的SpringMvc测试

对于前后端分离的项目而言,无法直接从前端静态代码中测试接口的正确性,因此可以通过MockMVC来模拟HTTP请求。基于RESTful风格的SpringMVC的测试,我们可以测试完整的Spring MVC流程,即从URL请求到控制器处理,再到视图渲染都可以测试。

作用是无需启动服务器,利用Mock API模拟测试,它的执行过程如下:

  1. perform执行一个请求
  2. get构造一个GET请求(这里可以是PUT、POST、DELETE、、、)
  3. accept接受的数据格式
  4. andExcept添加执行后的断言
  5. andDo添加结果处理器,例如print结果
  6. andReturn执行完毕返回结果

@Ruwith 是一个测试启动器,它需要的依赖项是Junit


springboot新建modules springboot新建接口_springboot新建modules_14



spring boot 热启动

在调试接口时,需要对代码进行修改,修改完后要重启Web应用,此时spring boot的热启动就突出它的优势。它可以在代码修改后,实时生效,而不用重启web应用。使用热启动需要在pom.xml中引入spring-boot-devtolls,然后设置Optional为true,这个依赖项在创建工程时,可以选择


springboot新建modules springboot新建接口_springboot新建modules_15