今天使用 Maven 的单元测试,正常导入以下的类
org.junit.Assert;
org.junit.After;
org.junit.Before;
org.junit.Test;
在项目的根目录下执行 mvn test,结果并没有执行单元测试,也是无语了。普通的 Java 项目可以正常运行,但是 Maven Web Java 工程,通过 mvn test 命令却无法成功执行测试用例。
后来网络上查看了资料,maven-surefire-plugin
不支持以前的 Test 注解了,需要依赖 junit-jupiter-api:5.7.0
,使用里面的测试注解。
具体区别如下:
注解位于 org.junit.jupiter.api
包中。
断言位于 org.junit.jupiter.api.Assertions
类中。
假设位于 org.junit.jupiter.api.Assumptions
类中。
@Before
和 @After
不再存在;使用 @BeforeEach
和 @AfterEach
@BeforeClass
和 @AfterClass
不再存在;使用 @BeforeAll
和 @AfterAll
@Ignore
不再存在;使用 @Disabled
@Category
不再存在;使用 @Tag
。
@RunWith
不再存在;使用 @ExtendWith
@Rule
和 @ClassRule
不再存在;使用 @ExtendWith
和 @RegisterExtension
所以测试用例如下所示,导入 org.junit.jupiter.api 包下的类和注解,不要导入 org.junit 包下的类和注解:
package com.example.demo02;import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;/*** description** @author liaowenxiong* @date 2022/1/28 08:18*/public class HelloMavenTest {private HelloMaven hm;@BeforeEachpublic void setUp() {hm = new HelloMaven();}@Testpublic void testAdd() throws InterruptedException {int a = 1;int b = 2;int result = hm.add(a, b);Assertions.assertEquals(a + b, result);}@Testpublic void testSubtract() throws InterruptedException {int a = 1;int b = 2;int result = hm.subtract(a, b);Assertions.assertEquals(a - b, result);}@AfterEachpublic void tearDown() throws Exception {System.out.println("测试结束了!");}
}
对应的 pom.xml 配置内容:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example.mvnbook</groupId><artifactId>hello-world</artifactId><version>1.0-SNAPSHOT</version><name>Maven Hello World Project</name><dependencies><!-- 必须使用junit-jupiter-api构件,测试注解、断言都源于此构件--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.8.2</version><scope>test</scope></dependency></dependencies><build><pluginManagement><plugins><!-- 必须显式的声明测试插件,否则无法执行测试 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>3.0.0-M5</version></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.9</source><target>1.9</target><encoding>UTF-8</encoding></configuration></plugin></plugins></pluginManagement></build>
</project>