springboot--单元测试

单元测试

  • 前言
  • 1、写测试要用的类
  • 2、写测试要用的类
  • 3、运行测试类
  • 4、spring-boot-starter-test默认提供了以下库
    • [4.1 junit5](#4.1 junit5)
      • [4.1.1 @DisplayName:为测试类或者测试方法设置展示名称](#4.1.1 @DisplayName:为测试类或者测试方法设置展示名称)
      • [4.1.2 @BeforeAll:所有测试方法运行之前先运行这个](#4.1.2 @BeforeAll:所有测试方法运行之前先运行这个)
      • [4.1.3 @BeforeEach:每个测试方法运行之前运行](#4.1.3 @BeforeEach:每个测试方法运行之前运行)
    • [4.2 断言](#4.2 断言)
      • [4.2.1 Assertions.assertEquals](#4.2.1 Assertions.assertEquals)
      • 4.2.2嵌套测试
      • [4.2.3参数话测试 @ParameterizedTest](#4.2.3参数话测试 @ParameterizedTest)

前言

Spring boot 提供一系列测试工具集及注释方便我们进行测试

spring-boot-test提供核心测试能力,spring-boot-test-autoconfigure 提供测试的一些自动化配置

我们只需导入spring-boot-starter-test即可整合测试


1、写测试要用的类

javascript 复制代码
package com.example.boot306demo.service;

import org.springframework.stereotype.Service;

/**
 * @author jitwxs
 * @date 2023年11月15日 20:27
 */
@Service
public class HelloService {
    public int sum(int a,int b){
        return a+b;
    }
}

2、写测试要用的类

自动注入任意组件即可测试

javascript 复制代码
package com.example.boot306demo;

import com.example.boot306demo.service.HelloService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest  //具备测试springboot应用容器中所有组件的功能
class Boot306DemoApplicationTests {
    @Autowired //自动注入任意组件即可测试
    HelloService helloService;

    @Test
    void contextLoads() {
        int sum = helloService.sum(1,2);
        System.out.println(sum);
    }
}

3、运行测试类

4、spring-boot-starter-test默认提供了以下库

junit5/spring Test/Assertj/Hamcrest/Mockito/JSONassert/jsonPath

4.1 junit5

官方英文文档为:https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

中文文档:https://gitee.com/liushide/junit5_cn_doc/blob/master/junit5UserGuide_zh_cn.md

4.1.1 @DisplayName:为测试类或者测试方法设置展示名称

4.1.2 @BeforeAll:所有测试方法运行之前先运行这个

4.1.3 @BeforeEach:每个测试方法运行之前运行

4.2 断言

Assertions

4.2.1 Assertions.assertEquals



4.2.2嵌套测试

junit5 可以通过java中的内部类和@Nested注解实现嵌套测试,从而可以更好的把相关的测试方法组织在一起,在内部类中可以使用@BeforeEach和@AfterEach注解,而且嵌套的层次没有限制

4.2.3参数话测试 @ParameterizedTest

javascript 复制代码
@ParameterizedTest //参数话测试
    @ValueSource(strings = {"one","two","three"})
    @DisplayName("参数话测试")
    public void parameterizedTest(String string){
        System.out.println(string);
        Assertions.assertTrue(StringUtils.isNotBlank(string));
    }


相关推荐
程序猿小D16 分钟前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的个人财务管理系统,推荐!
java·数据库·mysql·spring·毕业论文·ssm框架·个人财务管理系统
jack_yin1 小时前
Telegram DeepSeek Bot 管理平台 发布啦!
后端
小码编匠1 小时前
C# 上位机开发怎么学?给自动化工程师的建议
后端·c#·.net
库森学长1 小时前
面试官:发生OOM后,JVM还能运行吗?
jvm·后端·面试
转转技术团队1 小时前
二奢仓店的静默打印代理实现
java·后端
蓝易云1 小时前
CentOS 7上安装X virtual framebuffer (Xvfb) 的步骤以及如何解决无X服务器的问题
前端·后端·centos
钢铁男儿1 小时前
C# 接口(什么是接口)
java·数据库·c#
丶小鱼丶1 小时前
排序算法之【归并排序】
java·排序算法
上上迁1 小时前
分布式生成 ID 策略的演进和最佳实践,含springBoot 实现(Java版本)
java·spring boot·分布式
永日456701 小时前
学习日记-spring-day42-7.7
java·学习·spring