SpringBoot第二十二天 - JUnit单元测试

SpringBoot - JUnit单元测试

本节学习SpringBoot使用Junit进行单元测试。

1. JUnit概述

1.1 JUnit简介

JUnit 5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing.
JUnit 5 is the result of JUnit Lambda and its crowdfunding campaign on Indiegogo.

About - JUnit 5

JUnit是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个。JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。
JUnit是由 Erich Gamma 和 Kent Beck 编写的一个回归测试框架(regression testing framework)。Junit测试是程序员测试,即所谓白盒测试,因为程序员知道被测试的软件如何(How)完成功能和完成什么样(What)的功能。Junit是一套框架,继承TestCase类,就可以用Junit进行自动测试了。

junit - 百度百科

1.2 JUnit5特性

作为最新版本的JUnit框架,JUnit5与之前版本的JUnit框架有很大的不同。由三个不同子项目的几个不同模块组成:

Unlike previous versions of JUnit, JUnit 5 is composed of several different modules from three different sub-projects.

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

The JUnit Platform serves as a foundation for launching testing frameworks on the JVM. It also defines the TestEngine API for developing a testing framework that runs on the platform. Furthermore, the platform provides a Console Launcher to launch the platform from the command line and a JUnit 4 based Runner for running any TestEngine on the platform in a JUnit 4 based environment. First-class support for the JUnit Platform also exists in popular IDEs (see IntelliJ IDEA, Eclipse, NetBeans, and Visual Studio Code) and build tools (see Gradle, Maven, and Ant).

JUnit Jupiter is the combination of the new programming model and extension model for writing tests and extensions in JUnit 5. The Jupiter sub-project provides a TestEngine for running Jupiter based tests on the platform.

JUnit Vintage provides a TestEngine for running JUnit 3 and JUnit 4 based tests on the platform. It requires JUnit 4.12 or later to be present on the class/module path.

What is JUnit 5? - JUnit 5 User Guide

JUnit Platform:JUnit Platform是在JVM上启动测试框架的基础,不仅支持JUnit自制的测试引擎,其他测试引擎也都可以接入。

JUnit Jupiter:JUnit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部包含了一个测试引擎,用于在JUnit Platform上运行。

JUnit Vintage:由于JUnit已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit 4.x,JUnit 3.x的测试引擎。

1.3 SpringBoot整合JUnit

SpringBoot 2.2.0版本开始引入JUnit5作为单元测试默认库。SpringBoot 2.4以上移除了默认对JUnit Vintage的依赖,如果需要兼容JUnit4需要自行引入。

JUnit 5’s Vintage Engine Removed from spring-boot-starter-test

If you upgrade to Spring Boot 2.4 and see test compilation errors for JUnit classes such as org.junit.Test, this may be because JUnit 5’s vintage engine has been removed from spring-boot-starter-test. The vintage engine allows tests written with JUnit 4 to be run by JUnit 5. If you do not want to migrate your tests to JUnit 5 and wish to continue using JUnit 4, add a dependency on the Vintage Engine, as shown in the following example for Maven:

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Spring Boot 2.4 Release Notes - GitHub/Spring-projects

2. 单元测试的基本使用

2.1 导入单元测试模块starter

Maven引入SpringBoot单元测试模块starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <!-- 使用SpringBoot的版本管理机制 -->
</dependency>

2.2 编写并分析简单测试类

现有业务层需要对其CRUD功能进行测试:

@Service
public class UserServiceImpl implements UserService {
   
    private UserMapper mapper;
    @Autowired
    public void setMapper(UserMapper mapper) {
   
        this.mapper = mapper;
    }
    /**
     * 根据ID获取用户记录
     * 
     * @param id ID
     * @return 用户记录
     */
    public User getUserById(int id) {
   
        return mapper.selectUserById(id);
    }
}

根据上述代码编写简单测试类测试其CRUD功能:

@SpringBootTest
@Slf4j
public class TestUserServiceImpl {
   
    private UserService service;
    @Autowired
    public void setService(UserService service) {
   
        this.service = service;
    }
    @Test
    public void testGetUserById() {
   
        log.info("测试参数:{},测试结果:{}", 1, service.getUserById(1));
    }
}

运行测试方法,控制台打印结果:

2021-10-12 10:32:25.709  INFO 6420 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-10-12 10:32:25.927  INFO 6420 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2021-10-12 10:32:25.979  INFO 6420 --- [           main] pers.dyj123.test.TestUserServiceImpl     : 测试参数:1,测试结果:Account(id=1, name=张三, age=24)

简单分析测试类:

  • 测试类需用@SpringBootTest注解,表明这是一个SpringBoot的测试类
  • @Test测试方法可直接运行,无需编写main方法;
  • SpringBoot的测试类可以使用Spring功能(使用@Autowired自动装配功能等);
  • 测试类及测试方法命名规范:测试类命名需按照Test+需要测试的类名,测试方法需按照test+需要测试的方法名

3. JUnit5常用注解

JUnit5提供了非常多的常用注解,JUnit5的注解相较JUnit4的注解有所变化:

注解 功能
@Test 表示方法是测试方法。但是与JUnit4的@Test不同,它的职责非常单一不能声明任何属性,
拓展的测试将会由Jupiter提供额外测试
@ParameterizedTest 表示测试方法是参数化测试,后半部分将详细介绍
@RepeatedTest 表示测试方法可重复执行
@DisplayName 为测试类或者测试方法设置展示名称
@BeforeEach 标注此注解的方法会在每个测试方法执行之前执行
@AfterEach 标注此注解的方法会在每个测试方法执行之后执行
@BeforeAll 标注此注解的方法会在所有测试方法执行之前执行
@AfterAll 标注此注解的方法会在所有测试方法执行之后执行
@Tag 表示单元测试类别,类似JUnit4中的@Catagories
@Disabled 表示测试类或者测试方法不执行,类似JUnit4中的@Ignore
@Timeout 表示测试方法运行如果超过了指定时间将会返回错误
@ExtendWith 为测试类或者测试方法提供扩展类引用

关于更多注解的介绍与使用方式可以参考

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值