Spring MVC 集成新版JUnit 5 测试框架

JUnit 是一个回归测试框架(regression testing framework)

在项目的pom.xml 配置文件中添加最新的JUnit 5 依赖:

注释junit 4 依赖,引入 junit 5 依赖。

<!-- junit start -->

<!--<dependency>-->

<!--<groupId>junit</groupId>-->

<!--<artifactId>junit</artifactId>-->

<!--<version>4.12</version>-->

<!--<scope>test</scope>-->

<!--</dependency>-->

<dependency>

<groupId>org.junit.jupiter</groupId>

<artifactId>junit-jupiter-api</artifactId>

<version>RELEASE</version>

<scope>test</scope>

</dependency>

<!-- junit end -->

Spring MVC 集成新版JUnit 5 测试框架

在test 项目中,创建测试基类: BaseJunit4Test,具体代码如下:

package com.rickie;

import org.junit.jupiter.api.extension.ExtendWith;

//import org.junit.runner.RunWith;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit.jupiter.SpringExtension;

//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//@RunWith(SpringJUnit4ClassRunner.class)

@ExtendWith(SpringExtension.class)

@ContextConfiguration(locations={"classpath:applicationContext.xml"})

public class BaseJunit4Test {

}

参考链接:

JUnit 5 User Guide

https://junit.org/junit5/docs/current/user-guide/#overview-what-is-junit-5

测试类新注解 New Annotations for Running Tests

The @RunWith was used to integrate the test context with other frameworks or to change the overall execution flow in the test cases in JUnit 4.

With JUnit 5, we can now use the @ExtendWith annotation to provide similar functionality.

As an example, to use the Spring features in JUnit 4:

在JUnit 4 版本中,使用 @RunWith 集成测试环境和其他框架。

在JUnit 5 版本中,我们现在使用 @ExtendWith 注解提供相同的功能。

如下示例代码,是JUnit 4:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(

{"/app-config.xml", "/test-data-access-config.xml"})

public class SpringExtensionTest {

/*...*/

}

Now, in JUnit 5 it is a simple extension:

现在,JUnit 5 示例代码,如下所示:

@ExtendWith(SpringExtension.class)

@ContextConfiguration(

{ "/app-config.xml", "/test-data-access-config.xml" })

public class SpringExtensionTest {

/*...*/

}

创建一个具体的测试类,简单测试集成 JUnit 框架是否成功:

package com.rickie.dao;

import com.rickie.BaseJunit4Test;

import com.rickie.model.User;

import org.junit.jupiter.api.DisplayName;

import org.junit.jupiter.api.Test;

import javax.annotation.Resource;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class UserDaoTest extends BaseJunit4Test {

@Resource

private UserDao userDao;

@Test

@DisplayName("用户列表测试")

public void findAll() {

List<User> userList = userDao.findAll();

System.out.println("userList.size()=" + userList.size());

assertTrue(userList.size() > 0);

}

}

测试输出结果:

Spring MVC 集成新版JUnit 5 测试框架

相关推荐