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

简介: JUnit 是一个 Java 编程语言的单元测试框架。JUnit 在测试驱动的开发方面有很重要的发展,是起源于 JUnit 的一个统称为 xUnit 的单元测试框架之一。
Junit4Junit5区别非常大,高版本的 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版本差异

Junit4Junit5区别非常大,高版本的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的集成。

相关文章
|
10天前
|
安全 Java 测试技术
Spring Boot集成支付宝支付:概念与实战
【4月更文挑战第29天】在电子商务和在线业务应用中,集成有效且安全的支付解决方案是至关重要的。支付宝作为中国领先的支付服务提供商,其支付功能的集成可以显著提升用户体验。本篇博客将详细介绍如何在Spring Boot应用中集成支付宝支付功能,并提供一个实战示例。
35 2
|
10天前
|
Java 关系型数据库 数据库
Spring Boot多数据源及事务管理:概念与实战
【4月更文挑战第29天】在复杂的企业级应用中,经常需要访问和管理多个数据源。Spring Boot通过灵活的配置和强大的框架支持,可以轻松实现多数据源的整合及事务管理。本篇博客将探讨如何在Spring Boot中配置多数据源,并详细介绍事务管理的策略和实践。
36 3
|
1天前
|
测试技术
测试基础 Junit单元测试框架
测试基础 Junit单元测试框架
7 2
测试基础 Junit单元测试框架
|
2天前
|
JavaScript Java 开发者
Spring Boot中的@Lazy注解:概念及实战应用
【4月更文挑战第7天】在Spring Framework中,@Lazy注解是一个非常有用的特性,它允许开发者控制Spring容器的bean初始化时机。本文将详细介绍@Lazy注解的概念,并通过一个实际的例子展示如何在Spring Boot应用中使用它。
13 2
|
9天前
|
Java 调度 Maven
Springboot实战篇--Springboot框架通过@Scheduled实现定时任务
Spring Boot的Scheduled定时任务无需额外Maven依赖,通过`@EnableScheduling`开启。任务调度有两种方式:fixedRate和fixedDelay,前者任务结束后立即按设定间隔执行,后者在任务完成后等待设定时间再执行。更灵活的是cron表达式,例如`0 0 3 * * ?`表示每天3点执行。实现定时任务时,需注意默认单线程执行可能导致的任务交错,可通过自定义线程池解决。
|
9天前
|
缓存 NoSQL Java
springboot业务开发--springboot集成redis解决缓存雪崩穿透问题
该文介绍了缓存使用中可能出现的三个问题及解决方案:缓存穿透、缓存击穿和缓存雪崩。为防止缓存穿透,可校验请求数据并缓存空值;缓存击穿可采用限流、热点数据预加载或加锁策略;缓存雪崩则需避免同一时间大量缓存失效,可设置随机过期时间。文章还提及了Spring Boot中Redis缓存的配置,包括缓存null值、使用前缀和自定义过期时间,并提供了改造代码以实现缓存到期时间的个性化设置。
|
9天前
|
XML Java API
Spring Boot 整合 LiteFlow 规则引擎:概念与实战
【4月更文挑战第30天】在现代软件开发中,规则引擎允许我们以声明式的方式定义业务逻辑和决策路径。LiteFlow 是一个轻量级、易于使用的组件式规则引擎,它可以与 Spring Boot 应用无缝整合。本文将介绍如何在 Spring Boot 项目中引入 LiteFlow,实现灵活的业务流程管理。
27 0
|
9天前
|
开发框架 Java Maven
SpringBoot-Starter 概念与实战
【4月更文挑战第30天】Spring Boot 是一个基于 Spring Framework 的开发框架,旨在简化 Spring 应用程序的搭建和开发。Spring Boot 提供了大量的 Starter(启动器)来简化项目的依赖管理和配置,其中最为常见的是 SpringBoot-Starter。
27 1
|
10天前
|
安全 Java 测试技术
利用Java反射机制提高Spring Boot的代码质量:概念与实战
【4月更文挑战第29天】Java反射机制提供了一种强大的方法来在运行时检查或修改类和对象的行为。在Spring Boot应用中,合理利用反射可以提高代码的灵活性和可维护性。本篇博客将探讨Java反射的核心概念,并展示如何通过反射提高Spring Boot项目的代码质量。
28 0
|
10天前
|
监控 Java 测试技术
Spring Boot与事务钩子函数:概念与实战
【4月更文挑战第29天】在复杂的业务逻辑中,事务管理是确保数据一致性和完整性的关键。Spring Boot提供了强大的事务管理机制,其中事务钩子函数(Transaction Hooks)允许开发者在事务的不同阶段插入自定义逻辑。本篇博客将详细探讨事务钩子函数的概念及其在Spring Boot中的应用。
31 1

热门文章

最新文章