今天使用 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;
@BeforeEach
public void setUp() {
hm = new HelloMaven();
}
@Test
public void testAdd() throws InterruptedException {
int a = 1;
int b = 2;
int result = hm.add(a, b);
Assertions.assertEquals(a + b, result);
}
@Test
public void testSubtract() throws InterruptedException {
int a = 1;
int b = 2;
int result = hm.subtract(a, b);
Assertions.assertEquals(a - b, result);
}
@AfterEach
public void tearDown() throws Exception {
System.out.println("测试结束了!");
}
}
对应的 pom.xml 配置内容:
4.0.0
com.example.mvnbook
hello-world
1.0-SNAPSHOT
Maven Hello World Project
org.junit.jupiter
junit-jupiter-api
5.8.2
test
org.apache.maven.plugins
maven-surefire-plugin
3.0.0-M5
org.apache.maven.plugins
maven-compiler-plugin
1.9
1.9
UTF-8