一、单元测试
介绍
① 在开发中,当完成一个功能接口或者业务方法的编写后,通常借助单元测试来验证该功能是否正确。
② spring boot项目进行单元测试时,需要提前在pom.xml中添加spring-boot-starter-test
(测试依赖启动器),然后通过相关注解实现单元测试
③ 注明:本文的代码用到入门程序spring initializr的代码
1. 添加测试依赖启动器
spring-boot-starter-test
:测试依赖启动器
使用Spring Initializr创建项目时,pom.xml中会自动加入该依赖,不用自己手动加了
<!--测试依赖启动器:spring-boot-starter-test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2. 编写单元测试类和测试方法
使用SpringInitializr创建项目时,会在src.test.java测试目录下自动创建与项目主程序启动类对应的单元测试类
目录结构:
编写单元测试类和测试方法
①
@RunWith(SpringRunner.class)
:测试运行器,加载SpringBoot测试注解(@SpringBootTest)
②@SpringBootTest
:标记该类为单元测试类,并加载项目的上下文环境ApplicationContext
③@Autowired
:自动注入HelloController类的对象(标在属性上)
@Autowired
private HelloController helloController;
④
@Test
:标记该方法为单元测试方法(在博客第15章泛型的JUnit中讲到)
package com.wpz.chapter01;
import com.wpz.chapter01.controller.HelloController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
//书上还有一句@RunWith(SpringRunner.class):测试运行器,加载SpringBoot测试注解(@SpringBootTest)
//@SpringBootTest:标记该类为单元测试类,并加载项目的上下文环境ApplicationContext
@SpringBootTest
class Chapter01ApplicationTests {
//这里的目的:测试HelloController类中的hello()方法
//- 按照以前的方法来测试:先new一个HelloController对象,再用这个对象调用hello()方法
//- spring中的依赖注入,在springboot中也能用:用注解的方式将对象注入,无需自己new对象
//@Autowired:自动注入HelloController类的对象
@Autowired
private HelloController helloController;
//@Test:标记该方法为单元测试方法(在博客第15章泛型的JUnit中讲到)
@Test
void helloControllerTest() {
String hello = helloController.hello();//调用hello()进行测试
System.out.println(hello);//输出
}
}
3. 测试
输出:
二、热部署
介绍
① 开发中,通常会对一段业务代码不断地测试,在修改之后往往需要重启服务,有些服务需要加载很久才能启动成功,这种不必要的重复极大降低了程序开发效率
② 为此,spring boot框架专门提供了进行热部署的依赖启动器,用于进行项目热部署,而无须开发人员手动重启项目。
1. 添加热部署依赖启动器
spring-boot-devtools
:热部署依赖启动器,devtools译为开发者工具(热部署)
在pom.xml中添加依赖
<!--热部署依赖启动器:-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
2. Idea工具热部署配置
file - setting - compiler
按图片完成
3. 测试
启动项目,在浏览器中访问http://localhost:8080/hello
此时更改hello()中的return语句,但是不重新启动项目,刷新页面,看页面的显示
public String hello() {
// return "wpz say hello Spring Boot by Spring Initializr";
return "update";
}