Spring Boot项目单元测试、热部署与原理分析
对项目HelloWorld01进行单元测试
1、修改pom.xml文件,添加测试依赖启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、创建测试类与测试方法
在net.lhf.lesson01包里创建测试类TestHelloWorld01
package net.lhf.lesson01;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 功能:测试HelloWorld01
* 作者:李红芙
* 日期:2021年04月26日
*/
@RunWith(SpringRunner.class) //测试启动器,并加载Spring Boot测试注解
@SpringBootTest //标记Spring Boot单元测试,并加载applicationContext上下文环境
public class TestHelloWorld01 {
}
注入待测试类HelloWorld01Controller
创建测试方法contextLoad(),测试待测试类实例的方法
package net.lhf.lesson01;
import net.lhf.lesson01.controller.HelloWorld01Controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 功能:测试HelloWorld01
* 作者:李红芙
* 日期:2021年04月26日
*/
@RunWith(SpringRunner.class) //测试启动器,并加载Spring Boot测试注解
@SpringBootTest //标记Spring Boot单元测试,并加载applicationContext上下文环境
public class TestHelloWorld01 {
@Autowired
private HelloWorld01Controller helloWorld01Controller;
@Test
public void contextLoad(){
// 获取控制器hello()方法的返回值
String hello = helloWorld01Controller.hello();
// 在控制台输出hello()方法的返回值
System.out.println(hello);
}
}
运行测试
修改测试方法contextLoad()
测试失败,期望值和实际值不一样,修改值为一样的。
运行测试
测试成功
对项目HelloWorld02进行单元测试
利用Spring Initializr构建项目时自动生成的测试类。
总共添加了三个地方
package net.lhf.lesson01;
import net.lhf.lesson01.controller.HelloWorld02Controller;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class Helloworld02ApplicationTests {
//注入待测试类
@Autowired
private HelloWorld02Controller controller;
@Test
void contextLoads() {
String hello =controller.hello();
Assert.assertSame("<h3>你好,Spring Boot世界!</h3>",hello);
}
}
运行测试
测试成功
对项目HelloWorld01进行热部署
热部署配置
单击[file]->[settings]菜单项,打开设置对话框,找到complier,勾选择build project automatically使用快速键
按组合键Ctrl + Shift + Alt + /打开Maintenance对话框
热部署测试
运行启动类HelloWorld01Application
刚开始遇到错误,端口号8080被占用,所以需要换下他的端口号,
新建一个application.properties文件
修改里面的端口号
修改之后重新运行测试
在浏览器里访问http://localhost:8801/lhf01/hello
修改控制器HelloWorld01Controller代码