Spring Boot基础学习02 - Spring Boot项目单元测试、热部署与原理分析

一、Spring Boot 单元测试

(一)对项目HelloWorld01进行单元测试

1.修改pom.xml文件,添加测试依赖启动器

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

在这里插入图片描述
junit是在测试类中写注解符@RunWith生成的

2.创建测试类与测试方法

  • 在src/test/java里创建net.lbj.lesson01包,并在包里创建测试类TestHelloWorld01
    在这里插入图片描述
package net.lbj.lesson01;

import net.lbj.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
 * 20210426
 */
@RunWith(SpringRunner.class) //测试启动器,并加载Spring Boot测试注解
@SpringBootTest //标记Spring Boot单元测试,会自动加载Spring应用容器
public class TestHelloWorld01 {
    //注入待测试类
    @Autowired
    public HelloWorld01Controller controller;

    @Test
    public void testHello() {
        //获取控制器hello()方法的返回值
        String hello = controller.hello();
        //在控制台输出hello()方法的返回值
        System.out.println("hello()方法的返回值:" + hello);
    }
}
  • 运行测试方法testHello()
    在这里插入图片描述
  • 如果相判断待测试类的方法的返回值是不是指定的某个数据,那么我们可以利用Assert类的assertSame()方法来进行测试
  • 修改测试方法testHello()
    在这里插入图片描述
  • 运行测试方法testHello()
    在这里插入图片描述
    测试失败,抛出AssertionError(断言错误)
    期望值:Hello Spring Boot World!
    实际值:

    Hello Spring Boot World!

  • 再次修改测试方法testHello()
    在这里插入图片描述
  • 运行测试方法:在这里插入图片描述

(二)对项目HelloWorld02进行单元测试

构建项目时自动生成的测试类
在这里插入图片描述

  • 添加注解,注入待测试类,编写测试方法contextLoads()的测试代码
    在这里插入图片描述
  • 运行测试方法
    运行错误:
    在这里插入图片描述
    原因:没有注入@Autowired
    运行结果:
    在这里插入图片描述

二、Spring Boot热部署

(一)对项目HelloWorld01进行热部署

1.在pom.xml文件里添加开发工具依赖

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

在这里插入图片描述

2.热部署配置

  • 单击[file]->[settings]菜单项,打开设置对话框,找到complier,勾选择build project automatically (自动构建项目)
    在这里插入图片描述
  • 按组合键Ctrl + Shift + Alt + /打开Maintenance对话框
    在这里插入图片描述
  • 单击Registry选项,在Registry对话框里,勾选compiler.automake.allow.when.app.running,让程序在运行过程中也能自动编译
    在这里插入图片描述

3.热部署测试

  • 运行启动类HelloWorld01Application
    在这里插入图片描述
  • 在浏览器里访问http://localhost:8080/lbj01/hello
    在这里插入图片描述
  • 修改控制器HelloWorld01Controller代码,刷新浏览器,查看结果
    在这里插入图片描述
    由此可见,采用了热部署,修改了程序,不用重启项目,系统会在程序运行过程中自动编译,于是可以看到修改后程序的运行结果。

三、课后作业

任务1、对上一讲的课后作业StudentInfo项目进行单元测试(Information)
任务2、按照讲稿实现热部署,并针对项目StudentInfo进行热部署测试(Information)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值