Spring 6 and JUnit 5 组合

news2024/11/25 14:57:27

Spring 6 and JUnit 5 组合

Spring 6 and JUnit 5 只需引入相关的包,不过偶尔可能会出现 no tests were found,最后有解决方案。

引入相关依赖包

<dependencies>
    <dependency>
        <groupId>jakarta.annotation</groupId>
        <artifactId>jakarta.annotation-api</artifactId>
        <version>2.1.1</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.0.5</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>6.0.5</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.9.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>4.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.22</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

创建相关测试环境类

@Configuration
@ComponentScan("pr.iceworld.fernando.spring6.junit5")
public class TestConfig {
}

@ContextConfiguration(classes = TestConfig.class)
@ExtendWith(SpringExtension.class)
@Slf4j
class BaseTest {

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.openMocks(this);
        log.info("@BeforeEach");
    }

    @BeforeAll
    public static void staticInit() {
        log.info("@BeforeAll");
    }

    @AfterEach
    public void tearDown() {
        log.info("@AfterEach");
    }

    @AfterAll
    public static void staticFinished() {
        log.info("@AfterAll");
    }
}

编写测试用例

@DisplayName("This is a test class - for Fruit")
@Slf4j
public class TestFruit extends BaseTest {

    @InjectMocks
    FruitService fruitService;
    @Mock
    FruitRepository fruitRepository;

    @DisplayName("test get one fruit by id")
    @Test
    public void testGetOneFruitById() {
        Fruit apple = new Fruit();
        Long id = 301L;
        apple.setId(id);
        apple.setName("apple");
        when(fruitRepository.getById(id)).thenReturn(apple);
        Fruit foundFruit = fruitService.getFruitById(id);
        assertEquals(apple.getId(), foundFruit.getId());
    }

    @Disabled
    @Test
    public void testDisableMethod() {
        log.info("@Disabled, specific this method will still run, if run test whole class, this will be ignore");
    }

    @Disabled
    @Test
    public void testassertEqualsFailed() {
        assertEquals(5, 6);
    }

    @Disabled
    @Test
    public void testDisabledRuntimeException() {
        throw new RuntimeException("RuntimeException");
    }
}

创建对应的测试用例相关类及方法

public class Fruit {

    private Long id;
    private String name;
    // getter or setter
}
@Repository
public class FruitRepository {

    static List<Fruit> fruits = new ArrayList<>();

    public List<Fruit> getFruits() {
        return fruits;
    }

    public Fruit getById(Long id) {
        return fruits.stream().filter(e -> e.getId() == id).findFirst().orElseGet(() -> new Fruit());
    }

    public void save(Fruit fruit) {
        fruits.add(fruit);
    }
}
@Service
public class FruitService {

    @Resource
    FruitRepository fruitRepository;

    public List<Fruit> getFruits() {
        return fruitRepository.getFruits();
    }

    public void save(Fruit fruit) {
        fruitRepository.save(fruit);
    }

    public Fruit getFruitById(Long id) {
        return fruitRepository.getById(id);
    }
}

注意事项

@Disabled

全类测试,@Disabled 生效
在这里插入图片描述
方法测试,@Disabled 不生效
在这里插入图片描述

no tests were found

如果出现 no tests were found ,则对pom.xml更新

<!-- ... -->
    <dependency>
         <groupId>org.junit.platform</groupId>
         <artifactId>junit-platform-launcher</artifactId>
         <scope>test</scope>
     </dependency>
     <dependency>
         <groupId>org.junit.jupiter</groupId>
         <artifactId>junit-jupiter-engine</artifactId>
         <scope>test</scope>
     </dependency>
     <dependency>
         <groupId>org.junit.vintage</groupId>
         <artifactId>junit-vintage-engine</artifactId>
         <scope>test</scope>
     </dependency>
<!-- ... -->
<dependencyManagement>
     <dependencies>
         <dependency>
             <groupId>org.junit</groupId>
             <artifactId>junit-bom</artifactId>
             <version>5.9.2</version>
             <scope>import</scope>
             <type>pom</type>
         </dependency>
     </dependencies>
 </dependencyManagement>

 <build>
     <plugins>
         <plugin>
             <artifactId>maven-surefire-plugin</artifactId>
             <version>3.0.0-M9</version>
         </plugin>
         <plugin>
             <artifactId>maven-failsafe-plugin</artifactId>
             <version>3.0.0-M9</version>
         </plugin>
     </plugins>
 </build>

JUnit 5 注释

AnnotationDescription
@TestDenotes that a method is a test method. Unlike JUnit 4’s @Test annotation, this annotation does not declare any attributes, since test extensions in JUnit Jupiter operate based on their own dedicated annotations. Such methods are inherited unless they are overridden.
@ParameterizedTestDenotes that a method is a parameterized test. Such methods are inherited unless they are overridden.
@RepeatedTestDenotes that a method is a test template for a repeated test. Such methods are inherited unless they are overridden.
@TestFactoryDenotes that a method is a test factory for dynamic tests. Such methods are inherited unless they are overridden.
@TestTemplateDenotes that a method is a template for test cases designed to be invoked multiple times depending on the number of invocation contexts returned by the registered providers. Such methods are inherited unless they are overridden.
@TestClassOrderUsed to configure the test class execution order for @Nested test classes in the annotated test class. Such annotations are inherited.
@TestMethodOrderUsed to configure the test method execution order for the annotated test class; similar to JUnit 4’s @FixMethodOrder. Such annotations are inherited.
@TestInstanceUsed to configure the test instance lifecycle for the annotated test class. Such annotations are inherited.
@DisplayNameDeclares a custom display name for the test class or test method. Such annotations are not inherited.
@DisplayNameGenerationDeclares a custom display name generator for the test class. Such annotations are inherited.
@BeforeEachDenotes that the annotated method should be executed before each @Test, @RepeatedTest, @ParameterizedTest, or @TestFactory method in the current class; analogous to JUnit 4’s @Before. Such methods are inherited – unless they are overridden or superseded (i.e., replaced based on signature only, irrespective of Java’s visibility rules).
@AfterEachDenotes that the annotated method should be executed after each @Test, @RepeatedTest, @ParameterizedTest, or @TestFactory method in the current class; analogous to JUnit 4’s @After. Such methods are inherited – unless they are overridden or superseded (i.e., replaced based on signature only, irrespective of Java’s visibility rules).
@BeforeAllDenotes that the annotated method should be executed before all @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class; analogous to JUnit 4’s @BeforeClass. Such methods are inherited – unless they are hidden, overridden, or superseded, (i.e., replaced based on signature only, irrespective of Java’s visibility rules) – and must be static unless the “per-class” test instance lifecycle is used.
@AfterAllDenotes that the annotated method should be executed after all @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class; analogous to JUnit 4’s @AfterClass. Such methods are inherited – unless they are hidden, overridden, or superseded, (i.e., replaced based on signature only, irrespective of Java’s visibility rules) – and must be static unless the “per-class” test instance lifecycle is used.
@NestedDenotes that the annotated class is a non-static nested test class. On Java 8 through Java 15, @BeforeAll and @AfterAll methods cannot be used directly in a @Nested test class unless the “per-class” test instance lifecycle is used. Beginning with Java 16, @BeforeAll and @AfterAll methods can be declared as static in a @Nested test class with either test instance lifecycle mode. Such annotations are not inherited.
@TagUsed to declare tags for filtering tests, either at the class or method level; analogous to test groups in TestNG or Categories in JUnit 4. Such annotations are inherited at the class level but not at the method level.
@DisabledUsed to disable a test class or test method; analogous to JUnit 4’s @Ignore. Such annotations are not inherited.
@TimeoutUsed to fail a test, test factory, test template, or lifecycle method if its execution exceeds a given duration. Such annotations are inherited.
@ExtendWithUsed to register extensions declaratively. Such annotations are inherited.
@RegisterExtensionUsed to register extensions programmatically via fields. Such fields are inherited unless they are shadowed.
@TempDirUsed to supply a temporary directory via field injection or parameter injection in a lifecycle method or test method; located in the org.junit.jupiter.api.io package.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/385232.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

边界无限入选首届“网络安全高成长性企业”并荣获“勇创之星”

近日&#xff0c;由工业和信息化部、四川省人民政府主办的“2023年中国网络和数据安全产业高峰论坛网络安全产融合作分论坛”在成都举行&#xff0c;论坛上公布了“2022年度网络安全高成长性企业”名单。云原生安全、应用安全“灵动智御”理念创领者北京边界无限科技有限公司&a…

密码算法(SM1、SM2、SM3、SM4、同态加密、密态计算、隐私计算和安全多方计算)

文章目录SM1 对称密码SM2 椭圆曲线公钥密码算法SM3 杂凑算法SM4 对称算法同态加密密态计算和隐私计算安全多方计算技术安全多方计算的应用场景对称加密算法非对称加密算法&#xff08;公钥加密&#xff09;参考文章SM1、SM2、SM3和SM4 为了保障商用密码的安全性&#xff0c;国家…

HTTP#1 请求数据格式和响应数据格式

一. 简介概念Hyper Text Transfer Protocol (HTTP), 超文本传输协议, 规定了浏览器和服务器之间数据传输的规则HTTP协议特点1.基于TCP协议:面向连接&#xff0c;安全2.基于请求-响应模型的:一次请求对应一次响应3. HTTP协议是无状态的协议: 对于事务处理没有记忆能力, 每次请求…

JAVA中公平锁和非公平锁有什么区别?

从公平的角度来说,Java 中的锁总共可分为两类:公平锁和非公平锁。但公平锁和非公平锁有哪些区别? 正文 公平锁:每个线程获取锁的顺序是按照线程访问锁的先后顺序获取的,最前面的线程总是最先获取到锁。非公平锁:每个线程获取锁的顺序是随机的,并不会遵循先来先得的规则…

深眸科技|机器视觉提升制造性能,焕发传统企业智造新活力!

随着机器视觉技术的成熟与发展&#xff0c;其在工业制造中得到越来越广泛的应用。机器视觉在工业制造领域的应用朝着智能识别、智能检测、智能测量以及智能互联的完整智能体系方向发展。此外&#xff0c;快速变化的市场需求&#xff0c;不断涌入行业的竞争对手&#xff0c;让传…

操作系统真相还原_第8章:内存管理系统

文章目录8.1 Makefile 简介makefile基本语法make参数伪目标自定义变量与系统变量隐含规则自动化变量与模式规则8.2 实现assert断言操作系统代码编译、链接并写入磁盘启动bochs执行物理内存使用情况8.3 实现字符串操作函数操作系统代码编译、链接并写入磁盘启动bochs执行物理内存…

C++基础(一)—— C++概述、C++对C的扩展(作用域、struct类型、引用、内联函数、函数默认参数、函数占位参数、函数重载)

1. C概述1.1 c简介“c”中的来自于c语言中的递增运算符&#xff0c;该运算符将变量加1。c起初也叫”c withclsss”.通过名称表明&#xff0c;c是对C的扩展&#xff0c;因此c是c语言的超集&#xff0c;这意味着任何有效的c程序都是有效的c程序。c程序可以使用已有的c程序库。为什…

Halcon数据结构

1.HTuple类型 1、既可以表示的类型有int&#xff0c;double、float、string&#xff0c;既可以表示单个值&#xff1b; 2、可以是容器&#xff1b; 3、可以是数组&#xff0c;数组遍历时需要有下标&#xff0c;如&#xff1a;变量名称[下标] 图像数据类型 Byte&#xff1a;8…

药房管理系统;药库管理系统

第一&#xff0c;主要功能&#xff1a;  本系统集日常销售、药品进销存、会员积分、GSP管理等药店所需的所有功能于一体&#xff0c;实现店铺管理的全部自动化。第二、新功能&#xff1a;  增加了“按功能查询药品”的功能&#xff0c;使软件用户可以根据客户的症状推荐合适…

【进阶】2、搭建K8s集群【v1.23】

[toc] 一、安装要求 在开始之前&#xff0c;部署Kubernetes集群机器需要满足以下几个条件&#xff1a; 一台或多台机器&#xff0c;操作系统 CentOS7.x-86_x64硬件配置&#xff1a;2GB或更多RAM&#xff0c;2个CPU或更多CPU&#xff0c;硬盘30GB或更多集群中所有机器之间网络…

编写SPI_Master驱动程序_老方法

编写SPI_Master驱动程序 文章目录编写SPI_Master驱动程序参考资料&#xff1a;一、 SPI驱动框架1.1 总体框架1.2 怎么编写SPI_Master驱动1.2.1 编写设备树1.2.2 编写驱动程序二、 编写程序2.1 数据传输流程2.2 写代码致谢参考资料&#xff1a; 内核头文件&#xff1a;include\…

数字IC手撕代码--联发科(总线访问仲裁)

题目描述当A、B两组的信号请求访问某个模块时&#xff0c;为了保证正确的访问&#xff0c;需要对这些信号进行仲裁。请用Verilog实现一个仲裁器&#xff0c;对两组请求信号进行仲后&#xff0c;要求&#xff1a;协议如图所示&#xff0c;请求方发送req&#xff08;request&…

数据推荐 | 人体行为识别数据集

人体行为识别任务旨在通过对人体姿态进行分析&#xff0c;识别出人体的具体动作&#xff0c;为人体行为预测、突发事件处理、智能健身、智能看护等领域提供技术支持。 图片 图片 人体行为识别数据标注方式 人体行为数据通用的标注方式包括人体关键点标注和动作标签标注&#…

Spring Boot 整合分布式缓存 Memcached

Memcached是一个开源、高性能&#xff0c;将数据分布于内存中并使用key-value存储结构的缓存系统。它通过在内存中缓存数据来减少向数据库的频繁访问连接的次数&#xff0c;可以提高动态、数据库驱动之类网站的运行速度。 Memcached在使用是比较简单的&#xff0c;在操作上基本…

经典面试题:“从输入URL到展示出页面“这个过程发生了什么?

目录 &#x1f433;今日良言:在逆境中善待自己 &#x1f407;一、输入网址(URL) &#x1f407;二、域名查询(DNS解析) &#x1f407;三、建立TCP连接 &#x1f407;四、发送HTTP/HTTPS请求 &#x1f407;五、服务器响应请求 &#x1f407;六、浏览器解析渲染页面 &…

Simple_SSTI_2

Simple_SSTI_2前言一、python类的内置属性二、解题步骤1.查看当前目录2. 打开flag文件得到flag前言 要想做到这个题&#xff0c;先要了解SSTI_2模板注入详解 一、python类的内置属性 先看如下一段代码&#xff1a; class Restaurant:"""类"""def…

存储的本质-学习笔记

1 经典案例 1.1 数据的流动 一条用户注册数据流动到后端服务器&#xff0c;持久化保存到数据库中。 1.2 数据的持久化 校验数据的合法性修改内存写入存储介质2 存储&数据库简介 2.1 存储系统特点 性能敏感、容易受硬件影响、存储系统代码既“简单”又“复杂”。 2.2 数…

从0到1实现单机记账APP原理与细节uniApp内含源码 (二)

单机记账APP演示及源码 具体演示如下面视频所示。免费下载地址&#xff1a;点击进入 预览APP下载地址&#xff1a;http://8.142.10.182:8888/down/aWHWeGaEQE2W.apk &#xff08;带宽很小所以下载速度慢&#xff09; 由于资源已经通过了&#xff0c;页面的样式这里就不写了&am…

蓝桥杯单片机组省赛十二届第一场(关于矩阵,温度ds18b20,时间ds1302的学习,以及继电器等外设的综合利用)

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录一、该题目如下二、使用步骤1.矩阵键盘实现2.温度传感器ds18b20的实现总结提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考 一、该题目如下 分…

使用Containerd搭建K8s集群【v1.25】

[toc] 一、安装要求 在开始之前,部署Kubernetes集群机器需要满足以下几个条件: 一台或多台机器,操作系统 CentOS7.x-86_x64硬件配置:2GB或更多RAM,2个CPU或更多CPU,硬盘30GB或更多集群中所有机器之间网络互通可以访问外网,需要拉取镜像禁止swap分区二、准备环境 角色IP…