Spring 整合 JUnit

时间:2022-07-26
本文章向大家介绍Spring 整合 JUnit,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1 简介

  JUnit 是一个 Java 语言的单元测试框架。它由 Kent Beck 和 Erich Gamma 建立,逐渐成为源于 Kent Beck 的 sUnit 的 xUnit 家族中最为成功的一个。 JUnit 有它自己的 JUnit 扩展生态圈。多数 Java 的开发环境都已经集成了JUnit 作为单元测试的工具。JUnit 是由 Erich Gamma 和 Kent Beck 编写的一个回归测试框架(regression testing framework)。Junit 测试是程序员测试,即所谓白盒测试,因为程序员知道被测试的软件如何(How)完成功能和完成什么样(What)的功能。Junit 是一套框架,继承 TestCase 类,就可以用 Junit 进行自动测试了。

1.2 Spring 整合 JUnit4

1.2.1 相关依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

1.2.2 测试类

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/8/24
 * @description 测试类
 */
// 单元测试框架
@RunWith(value = SpringJUnit4ClassRunner.class)
// 加载配置文件
@ContextConfiguration(value = "classpath:application.xml")
public class RunDemo {
    @Test
    public void run() {
        System.out.println("run...");
    }
}

1.3 Spring 整合 JUnit5

1.3.1 相关依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.4.1</version>
</dependency>

1.3.2 测试类

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/8/24
 * @description 测试类
 */
@ExtendWith(value = SpringExtension.class)
@ContextConfiguration(value = "classpath:application.xml")
public class RunDemo {

    @Autowired
    private MyTarget myTarget;

    @Test
    public void run() {
        myTarget.run();
    }
}

1.3.2 复合注解

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/8/24
 * @description 测试类
 */
 // 可用次复合注解代替 @ExtendWith 和 @ContextConfiguration 两个注解
@SpringJUnitConfig(locations = "classpath:application.xml")
public class RunDemo {

    @Autowired
    private MyTarget myTarget;

    @Test
    public void run() {
        myTarget.run();
    }
}