SpringBoot开发入门1.2:单元测试和热部署


一、单元测试

介绍

① 在开发中,当完成一个功能接口或者业务方法的编写后,通常借助单元测试来验证该功能是否正确。
② 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";
}

在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值