Maven的单元测试没有执行的问题
今天使用 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>總結
以上是生活随笔為你收集整理的Maven的单元测试没有执行的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IntelliJ IDEA修改项目的包名
- 下一篇: Sublime Text安装格式化xml