Gradle从0入门到实战系列【八】SpringBoot集成Junit单元测试

简介: JUnit 是一个 Java 编程语言的单元测试框架。JUnit 在测试驱动的开发方面有很重要的发展,是起源于 JUnit 的一个统称为 xUnit 的单元测试框架之一。
Junit4和 Junit5区别非常大,高版本的 springboot(如:2.6.5)只有 junit5没有引入 junit4,但是低版本 springboot(如:2.1.8.RELEASE)的默认引入的是 junit4。

初始化项目,访问spring init,创建完成后导入IDEA中
image.png

修改repositories为阿里云的镜像

repositories {
    maven { url 'https://maven.aliyun.com/repository/central' }
    mavenCentral()
}

Junit版本差异

Junit4和Junit5区别非常大,高版本的springboot(如:2.6.5)只有junit5没有引入junit4,但是低版本springboot(如:2.1.8.RELEASE)的默认引入的是junit4。

image.png

  • Junit Platform: Junit Platform是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。
  • Junit Jupiter: Junit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部 包含了一个测试引擎,用于在Junit Platform上运行。
  • Junit Vintage: 由于JUnit已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit4.x,Junit3.x的测试引擎。

junit4代码示例

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class Junit4Test {
    
    @Autowired
    private TestRestTemplate testRestTemplate;
    
    @Before
    public void testBefore(){
        System.out.println("before.. 每个Test都会执行一次");
    }
    @Test
    public void test1(){
        String t = testRestTemplate.getForObject("/index", String.class);
        System.out.println("toIndex:" + t);
    }
    @After
    public void TestAfter(){
        System.out.println("after... 每个Test都会执行一次");
    }
    
    @BeforeClass
    public static void initClass(){
        System.out.println("******测试开始初始化,必须是static方法,仅执行一次");
    }
    
    @AfterClass
    public static void endClass(){
        System.out.println("******测试结束初始化,必须是static方法,仅执行一次");
    }
}
//执行顺序是:@BeforeClass→@Before→@Test→@After→@AfterClass

junit5代码示例

//包名有变化
import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class Junit5Test {
    
    @BeforeAll
    public static void testBeforeAll() {
        System.out.println("表示在所有单元测试之前执行......");
    }
    
    @BeforeEach
    public void testBeforeEach() {
        System.out.println("类似于JUnit4的@Before 表示在每个单元测试之前执行......");
    }
    @AfterEach
    public void testAfterEach() {
        System.out.println("类似于JUnit4的@After 表示在每个单元测试之后执行......");
    }
    
    @DisplayName("测试类或测试方法声明一个自定义的显示名称")
    @Test
    public void testTwo() throws Exception {
        System.out.println("testTwo......");
    }
    
    /**
     * 规定方法超时时间。超出时间测试出异常
     * @throws InterruptedException
     */
    @Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
    @Test
    void testTimeout() throws InterruptedException {
        Thread.sleep(600);
    }
    
    @AfterAll
    public static void testAfterAll() {
        System.out.println("表示在所有单元测试之后执行......");
    }
}

更多的变化请自行查阅相关文档

build.gradle配置

//方式1
tasks.named('test') {
   useJUnitPlatform()
}

//方式2
test {
   useJUnitPlatform()
}

单元测试代码

  1. 主程序代码

    //application
    package com.it235.it235order
    @SpringBootApplication
    public class It235OrderApplication {
        public static void main(String[] args) {
            SpringApplication.run(It235OrderApplication.class, args);
        }
    }
    
    //controller
    package com.it235.it235order.rest;
    @RestController
    public class OrderController {
    
        @GetMapping("/index")
        public String index(){
            return "ok";
        }
    }
    
    //service
    package com.it235.it235order.service;
    public interface OrderService {
        String get(Long orderId);
    }
    
    @Service
    public class OrderServiceImpl implements OrderService {
        @Override
        public String get(Long orderId) {
            return "订单ID:" + orderId;
        }
    }
  2. 测试程序代码

    package com.it235.it235order;
    
    @SpringBootTest
    public class It235OrderApplicationTests {
    }
    
    package com.it235.it235order.order;
    import com.it235.it235order.It235OrderApplicationTests;
    import com.it235.it235order.service.OrderService;
    import org.junit.jupiter.api.*;
    import org.springframework.beans.factory.annotation.Autowired;
    //集成Tests类
    public class OrderTests extends It235OrderApplicationTests {
        @Autowired
        private OrderService orderService;
    
        @DisplayName("测试方法1")
        @Test
        void getOrderTest() {
            Long orderId = 1001L;
            String s = orderService.get(orderId);
            Assertions.assertEquals("订单ID:" + orderId , s );
        }
    
        @DisplayName("测试方法2")
        @Test
        void getOrderTest2() {
            Long orderId = 1002L;
            String s = orderService.get(orderId);
            Assertions.assertEquals("订单ID2:" + orderId , s );
        }
    }
    

单元测试执行命令

  1. 使用gradlew test命令执行

    .\gradlew.bat test
  2. build时跳过test

    .\gradlew build -x test

test闭包扩展参数

  1. 执行单元测试前jvm相关参数

    test {
        // Discover and execute JUnit4-based tests
        useJUnit()
    
        // Discover and execute TestNG-based tests
        useTestNG()
        
        // set a system property for the test JVM(s)
        systemProperty 'some.prop', 'value'
        
        // set heap size for the test JVM(s)
        minHeapSize = "128m"
        maxHeapSize = "512m"
        
        //实际执行:java -Xmx20m -Dspring.profiles.active=unit -XX:+UseG1GC -jar app.jar
        jvmArgs "-Xmx20m" ,"-Dspring.profiles.active=unit" , "-XX:+UseG1GC"
        
        //Junit5
        useJUnitPlatform()
    }
  2. 执行单元测试前拷贝资源文件

    //定义一个拷贝任务,将src/main/db目录文件拷贝至build中
    task copyDbResources(type: Copy) {
        from 'src/main/db'
        into 'build/resources/main/db'
    }
    
    test {
        useJUnitPlatform()
    }
    
    //将测试资源复制到测试资源目录
    processTestResources {
        dependsOn copyDbResources
    }
    
  3. 排除不被单元测试扫描的包

    test {
        // explicitly include or exclude tests
        include 'org/foo/**'
        exclude 'com/it235/it235order/order'
        
        useJUnitPlatform()
    }

总结

SpringBoot将Junit无缝整合后让单元测试变得更加简单,Gradle也只需要简单的配置即可完成Junit的集成。

目录
相关文章
|
数据采集 JSON JavaScript
Cypress 插件实战:让测试更稳定,不再“偶尔掉链子”
本文分享如何通过自定义Cypress插件解决测试不稳定的痛点。插件可实现智能等待、数据预处理等能力,替代传统硬性等待,有效减少偶发性失败,提升测试效率和可维护性。文内包含具体实现方法与最佳实践。
|
存储 关系型数据库 测试技术
玩转n8n测试自动化:核心节点详解与测试实战指南
n8n中节点是自动化测试的核心,涵盖触发器、数据操作、逻辑控制和工具节点。通过组合节点,测试工程师可构建高效、智能的测试流程,提升测试自动化能力。
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1709 3
|
Web App开发 人工智能 JavaScript
主流自动化测试框架的技术解析与实战指南
本内容深入解析主流测试框架Playwright、Selenium与Cypress的核心架构与适用场景,对比其在SPA测试、CI/CD、跨浏览器兼容性等方面的表现。同时探讨Playwright在AI增强测试、录制回放、企业部署等领域的实战优势,以及Selenium在老旧系统和IE兼容性中的坚守场景。结合六大典型场景,提供技术选型决策指南,并展望AI赋能下的未来测试体系。
|
存储 人工智能 算法
AI测试平台实战:深入解析自动化评分和多模型对比评测
在AI技术迅猛发展的今天,测试工程师面临着如何高效评估大模型性能的全新挑战。本文将深入探讨AI测试平台中自动化评分与多模型对比评测的关键技术与实践方法,为测试工程师提供可落地的解决方案。
|
缓存 监控 安全
电商API集成入门:从零开始搭建高效接口
在数字化电商时代,API集成成为企业提升效率、实现系统互联的关键。本文从零开始,逐步讲解如何搭建高效、可靠的电商API接口,适合初学者学习。内容涵盖API基础、认证安全、请求处理、性能优化等核心步骤,并提供Python代码示例与数学公式辅助理解。通过实践,读者可掌握构建优质电商API的技巧,提升用户体验与系统性能。
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1570 0
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
1650 2
Spring Boot 3.x 微服务架构实战指南
|
消息中间件 Ubuntu Java
SpringBoot整合MQTT实战:基于EMQX实现双向设备通信
本教程指导在Ubuntu上部署EMQX 5.9.0并集成Spring Boot实现MQTT双向通信,涵盖服务器搭建、客户端配置及生产实践,助您快速构建企业级物联网消息系统。
3452 1
|
人工智能 缓存 测试技术
Playwright进阶指南 (6) | 自动化测试实战
2025企业级测试解决方案全面解析:从单元测试到千级并发,构建高可用测试体系。结合Playwright智能工具,解决传统测试维护成本高、环境依赖强、执行效率低等痛点,提升测试成功率,内容从测试架构设计、电商系统实战框架、高级测试策略、Docker化部署、CI/CD集成及AI测试应用,助力测试工程师掌握前沿技术,打造高效稳定的测试流程。
Playwright进阶指南 (6) | 自动化测试实战

热门文章

最新文章

推荐镜像

更多