文章目录

  • 1、什么是单元测试?
  • 2、单元测试有哪些好处?
  • 3、Spring Boot 单元测试使用
  • 3.1 单元测试的实现步骤
  • 3.1.1 生成单元测试类
  • 3.1.2 添加单元测试代码
  • 4、简单的断言说明


1、什么是单元测试?

单元测试(unit testing),是指对软件中的最小可测试单元(方法)进⾏检查和验证的过程就叫单元测试。

单元测试是开发者编写的⼀⼩段代码,⽤于检验被测代码的⼀个很小的、很明确的(代码)功能是否正确。执⾏单元测试就是为了证明某段代码的执⾏结果是否符合我们的预期。如果测试结果符合我们的预期,称之为测试通过,否则就是测试未通过(或者叫测试失败)

2、单元测试有哪些好处?

  1. 可以非常简单、直观、快速的测试某一个功能是否正确
  2. 使用单元测试可以帮我们在打包的时候,发现一些问题,因为在打包之前,所以的单元测试必须通过,否则不能打包成功
  3. 使用单元测试,在测试功能的时候,可以不污染连接的数据库,也就是可以不对数据库进行任何改变的情况下,测试功能

3、Spring Boot 单元测试使用

Spring Boot 项⽬创建时会默认单元测试框架 spring-boot-test,⽽这个单元测试框架主要是依靠另⼀个著名的测试框架 JUnit 实现的,打开 pom.xml 就可以看到,以下信息是 Spring Boot 项⽬创建是⾃动添加的:

Spring boot配置测试 spring boot unit test_spring

spring-boot-starter-testMANIFEST.MF(Manifest ⽂件是⽤来定义扩展或档案打包的相关信息的)⾥⾯有具体的说明,如下信息所示:

Spring boot配置测试 spring boot unit test_spring_02

3.1 单元测试的实现步骤

3.1.1 生成单元测试类

测试哪个类就在哪个类中生成:

Spring boot配置测试 spring boot unit test_单元测试_03


Spring boot配置测试 spring boot unit test_junit_04


Spring boot配置测试 spring boot unit test_spring_05


最终⽣成的代码:

package com.example.demo.mapper;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class UserMapperTest {

    @Test
    void getUserById() {
    }
}

Spring boot配置测试 spring boot unit test_单元测试_06


这个时候,此⽅法是不能调⽤到任何单元测试的⽅法的,此类只⽣成了单元测试的框架类,具体的业务代码要⾃⼰填充。

3.1.2 添加单元测试代码

(1)配置单元测试的类添@SpringBootTest注解

Spring boot配置测试 spring boot unit test_spring boot_07


(2)添加单元测试的业务代码

package com.example.demo.mapper;

import com.example.demo.model.UserInfo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;
//表示当前单元测试运行在SpringBoot环境中
@SpringBootTest
class UserMapperTest {
    //@Autowired         //科学版的idea此行代码会报错
    @Resource
    private UserMapper userMapper;
    @Test
    void getUserById() {
        UserInfo userInfo=userMapper.getUserById(1);
        Assertions.assertNotNull(userInfo);
    }
}

针对使用@Autowired 注解时,科学版的idea此行代码会报错解释:⬇️

结论:@Autowired 来自Spring, @Mapper 来自MyBaits,所以有可能出现不兼容的问题,解决方案是使用JDK提供的@Resource 来注入Mapper。

测试结果如下:

Spring boot配置测试 spring boot unit test_junit_08

4、简单的断言说明

Spring boot配置测试 spring boot unit test_spring boot_09