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

相关文章
|
17天前
|
消息中间件 Java Kafka
Springboot集成高低版本kafka
Springboot集成高低版本kafka
|
23天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
246 0
|
28天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
394 0
|
1月前
|
NoSQL Java Redis
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
263 1
|
16天前
|
Java 测试技术
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
21 0
|
2天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
Java 测试技术
Java 中的单元测试和集成测试策略
【4月更文挑战第19天】本文探讨了Java开发中的单元测试和集成测试。单元测试专注于单一类或方法的功能验证,使用测试框架如JUnit,强调独立性、高覆盖率和及时更新测试用例。集成测试则验证模块间交互,通过逐步集成或模拟对象来检测系统整体功能。两者相辅相成,确保软件质量和降低修复成本。
|
7天前
|
监控 测试技术 数据安全/隐私保护
如何将代理IP集成到自动化测试框架中?
如何将代理IP集成到自动化测试框架中?
|
11天前
|
分布式计算 Hadoop 测试技术
Hadoop【基础知识 05】【HDFS的JavaAPI】(集成及测试)
【4月更文挑战第5天】Hadoop【基础知识 05】【HDFS的JavaAPI】(集成及测试)
38 8
|
12天前
|
缓存 自动驾驶 测试技术
如何进行有效的Apollo测试:单元测试和集成测试指南
如何进行有效的Apollo测试:单元测试和集成测试指南
41 13

热门文章

最新文章