SpringBoot单元测试和热部署

单元测试

官方文档:spring.io

  1. SpringBoot的单元测试,依赖于 spring-boot-start-test,使用spring初始化器初始化Springboot项目时,会自动引入该依赖。
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
  1. 编写单元测试类
@RunWith(SpringRunner.class) // 测试启动器,并加载Spring Boot测试注解
@SpringBootTest  // 标记为Spring Boot单元测试类,并加载项目的ApplicationContext上下文环境
class SpringbootDemoApplicationTests {
    @Autowired
    private DemoController demoController;
    // 自动创建的单元测试方法实例
    @Test
    void contextLoads() {
        String demo = demoController.demo();
        System.out.println(demo);
    }
}
  1. @SpringBootTest和SpringRunner.class
    1. SpringBootTest 注解,标记当前类为SpringBoot单元测试类,提供和加载SpringBoot的ApplicationContext加载。
    2. SpringRunner.class是SpringJUnit4ClassRunner的包装类,在Junit测试中,使用Spring的一些注解的话,就需要该Runner环境,用来告诉jUnit4使用Spring的测试支持环境。
    3. 在JUnit4时,需要将@RunWith(SpringRunner.class)添加到测试类中,但在JUnit 5 (Jupiter)环境时,可以不添加其等效的@ExtendWith注解,因为@SpringBootTest和其他@…Test注解,都包含了@ExtendWith注解。

热部署

介绍

详细参考:https://blog.csdn.net/qq_42217906/article/details/122541220
开发时,如果每次改动代码就重启项目就会很麻烦,SpringBoot框架,专门提供了进行热部署的依赖启动器。其深层原理是使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个ClassLoader加载会更改的类,称为 restart ClassLoader ,这样在有代码更改的时候,原来的restart ClassLoader 被丢弃,重新创建一个restart ClassLoader,由于需要加载的类相比较少,所以实现了较快的重启时间。

1.添加依赖

<!-- 引入热部署依赖 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
</dependency>

2.Idea勾选,自动编译

在这里插入图片描述

3.修改idea注册表,勾选项目运行时允许自动编译

在这里插入图片描述

4.手动编译

修改完代码,按快捷键Ctrl+F9,手动构建项目,或者只修改单个类文件的话,按Ctrl+Shift+F9,重新编译该类文件,即可触发重启服务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值