SpringBoot单元测试与热部署

111 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

一、单元测试

在完成一个功能接口或业务方法的编写后,通常借助单元测试验证接口的是否正确。SpringBoot提拱了单元测试的支持。

1、引入spring-boot-starter-test测试依赖启动器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2、在test下编写单元测试类与测试方法

图片1.png 单元测试类注解说明

@Runwith(SpringRunner.class)//测试运行器,加载SpringBoot测试注解@SpringBootTest

@SpringBootTest//标记单元测试类,加载项目的上下文环境ApplicationContext

@Test//标记测试方法

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
​
@RunWith(SpringRunner.class)//测试运行器,加载SpringBoot测试注解@SpringBootTest
@SpringBootTest//标记单元测试类,加载项目的上下文环境ApplicationContext
public class Demo01ApplicationTest {
​
    @Autowired//注入HelloController实例对象
    private HelloController helloController;
​
    @Test//标记测试方法
    public void  test(){
        String result = helloController.hello();
        System.out.println(result);
    }
}

3、运行测试方法

图片2.png

二、热部署

在编写代码的时候,通常需要不断修改代码测试,但是修改后的代码需要重启服务器才会生效。如果项目比较大的情况下,重启项目比较费时间,于是SpringBoot提供了热部署的依赖启动器,用于进行项目的热部署,而不需要开发人员手动重启服务

1、引入热部署依赖启动器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

2、IDEA工具进行热部署设置

第一步: 在【File】--->【Settings】--->【Build,Execution,Deployment】--->【Complier】,勾选Build project automatically(自动编译),单击【Apply 】--->【OK】

图片3.png

第二步:在项目任意页面使用组合键“Ctrl+Shift+Alt+/”,打开Maintenance选项框,打开Registry界面

找到“compiler.automake.allow.when.app.running”,勾选对应的Value值将程序运行方式设置为自动编译,然后单击【Close】

图片4.png

此后修改代码便不需要重启服务器,就能看到修改后的代码