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的集成。

目录
相关文章
|
7月前
|
Java 测试技术 数据库连接
【SpringBoot(四)】还不懂文件上传?JUnit使用?本文带你了解SpringBoot的文件上传、异常处理、组件注入等知识!并且带你领悟JUnit单元测试的使用!
Spring专栏第四章,本文带你上手 SpringBoot 的文件上传、异常处理、组件注入等功能 并且为你演示Junit5的基础上手体验
1115 3
|
10月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
679 3
|
10月前
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
879 0
第07课:Spring Boot集成Thymeleaf模板引擎
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
280 0
|
10月前
|
存储 人工智能 Java
Springboot集成AI Springboot3 集成阿里云百炼大模型CosyVoice2 实现Ai克隆语音(未持久化存储)
本项目基于Spring Boot 3.5.3与Java 17,集成阿里云百炼大模型CosyVoice2实现音色克隆与语音合成。内容涵盖项目搭建、音色创建、音频合成、音色管理等功能,适用于希望快速掌握Spring Boot集成语音AI技术的开发者。需提前注册阿里云并获取API Key。
|
Java 测试技术 开发者
在软件开发中,测试至关重要,尤以单元测试和集成测试为然
在软件开发中,测试至关重要,尤以单元测试和集成测试为然。单元测试聚焦于Java中的类或方法等最小单元,确保其独立功能正确无误,及早发现问题。集成测试则着眼于模块间的交互,验证整体协作效能。为实现高效测试,需编写可测性强的代码,并选用JUnit等合适框架。同时,合理规划测试场景与利用Spring等工具也必不可少。遵循最佳实践,可提升测试质量,保障Java应用稳健前行。
240 1
|
测试技术 开发者 UED
探索软件测试的深度:从单元测试到自动化测试
【10月更文挑战第30天】在软件开发的世界中,测试是确保产品质量和用户满意度的关键步骤。本文将深入探讨软件测试的不同层次,从基本的单元测试到复杂的自动化测试,揭示它们如何共同构建一个坚实的质量保证体系。我们将通过实际代码示例,展示如何在开发过程中实施有效的测试策略,以确保软件的稳定性和可靠性。无论你是新手还是经验丰富的开发者,这篇文章都将为你提供宝贵的见解和实用技巧。
|
JSON Dubbo 测试技术
单元测试问题之增加JCode5插件生成的测试代码的可信度如何解决
单元测试问题之增加JCode5插件生成的测试代码的可信度如何解决
297 2
单元测试问题之增加JCode5插件生成的测试代码的可信度如何解决
|
IDE 测试技术 持续交付
Python自动化测试与单元测试框架:提升代码质量与效率
【9月更文挑战第3天】随着软件行业的迅速发展,代码质量和开发效率变得至关重要。本文探讨了Python在自动化及单元测试中的应用,介绍了Selenium、Appium、pytest等自动化测试框架,以及Python标准库中的unittest单元测试框架。通过详细阐述各框架的特点与使用方法,本文旨在帮助开发者掌握编写高效测试用例的技巧,提升代码质量与开发效率。同时,文章还提出了制定测试计划、持续集成与测试等实践建议,助力项目成功。
336 5

热门文章

最新文章

推荐镜像

更多