原文: https://javatutorial.net/how-to-run-junit-test-with-maven
本教程将介绍如何使用 Maven 的 Surefire 插件运行单元测试。 如果您不熟悉单元测试,则可以按照本教程快速了解。

在我们的 Maven 项目中,我们需要以下强制性依赖项:
<dependencies><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>5.4.2</version><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>5.4.2</version><scope>test</scope></dependency></dependencies>
junit-jupiter-engine依赖项包含运行我们的单元测试的 JUnit Jupiter 测试引擎的实现。
junit-jupiter-api依赖项提供了 API,使我们能够编写使用 JUnit 5 的测试和扩展。
因此,让我们创建一个非常简单的 Java 文件:
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;public class Example1 {public static int getNumber() {return 5;}public static String getMeaningfulText() {return "Hello World";}}
现在,为它创建一个 Test 类:
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;public class TestExample1 {@Testpublic void testNumber() {assertEquals(5, Example1.getNumber());}@Testpublic void testMeaningfulText () {assertEquals(“Hello World”, Exampe1.getMeaningfulText ());}}
最后,我们可以使用mvn clean build运行程序,并且应该看到 Superfire 插件正在运行我们的单元测试
[INFO][INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ running-unit-tests ---[INFO]------------------------------------------------------- T E S T S-------------------------------------------------------Running net.javatutorial.junit5.JUnit5Example1Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.039 sec -in net.javatutorial.junit5.JUnit5Example1Results :Tests run: 1, Failures: 0, Errors: 0, Skipped: 0[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------
