如何使用 maven 在命令行去执行 Java 程序,以及,如何执行测试

运行 Java 的一个 Main 方法

我们知道,大多数情况下,我们想要运行一个 Java 程序,其实就是运行一个 Main 方法。即使是一个 Spring 应用,最终也是会执行主应用的 Main 方法的。

所以,这里所说的使用 maven 在命令行去执行 Java 程序,也就是去执行对应的类的 Main 方法。

首先,我们添加一个插件,

<!-- https://mvnrepository.com/artifact/org.codehaus.mojo/exec-maven-plugin --> 
<dependency>                                                                    
  <groupId>org.codehaus.mojo</groupId>                                          
  <artifactId>exec-maven-plugin</artifactId>                                    
  <version>3.1.1</version>                                                      
</dependency>                                                                   

并且,配置好这个插件,

<build>
  <pluginManagement>
    <plugins>
      <!-- to run java file with exec-maven-plugin -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.1.1</version>
        <configuration>
          <mainClass>com.fanyfull.App</mainClass>
          <arguments>
            <argument>First</argument>
            <argument>Second</argument>
          </arguments>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>

之后,就可以执行我们想要执行的类的 Main 方法了,这里我们只要去修改 <mainClass> 标签中的类即可。如果想要传递命令行参数,那么,可以去自定义这个 <arguments> 里面的参数。

我们这里的 App 类如下,

package com.fanyfull;

import java.util.Arrays;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        if (args.length > 0) {
            System.out.println(Arrays.toString(args));
        }
    }
}

然后,我们只需要在命令行执行以下命令即可,

mvn clean compile exec:java
❯ mvn clean compile exec:java
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------< com.fanyfull:demo01 >-------------------------
[INFO] Building demo01 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ demo01 ---
[INFO] Deleting /home/fanyfull/edisk/javaCodes/demo01/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ demo01 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/fanyfull/edisk/javaCodes/demo01/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ demo01 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /home/fanyfull/edisk/javaCodes/demo01/target/classes
[INFO] 
[INFO] --- exec-maven-plugin:3.1.1:java (default-cli) @ demo01 ---
Hello World!
[First, Second]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.982 s
[INFO] Finished at: 2023-12-03T11:34:13+08:00
[INFO] ------------------------------------------------------------------------

有时候,我们执行的时候不用 clean 参数也是可以的,

mvn compile exec:java

运行测试

方法和上面的类似,先添加依赖,配置插件,

<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin --> 
<dependency>                                                                               
  <groupId>org.apache.maven.plugins</groupId>                                              
  <artifactId>maven-surefire-plugin</artifactId>                                           
  <version>3.2.2</version>                                                                 
</dependency>                                                                              
<!-- to run tests with maven-surefire-plugin --> 
<plugin>                                         
  <groupId>org.apache.maven.plugins</groupId>    
  <artifactId>maven-surefire-plugin</artifactId> 
  <version>3.2.2</version>                       
</plugin>                                        

然后,我们看一下测试的类,

package com.fanyfull;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * Unit test for simple App.
 */
public class AppTest {
    /**
     * Rigorous Test :-)
     */
    @Test
    public void justAnExample() {
        System.out.println("fany test");
        Assertions.assertThat("App").endsWith("pp");
    }


    @Test
    public void exampleTest02() {
        System.out.println("fany test02");
        Assertions.assertThat("App").endsWith("pp");
    }
}

之后,在命令行执行,

mvn test

结果如下,

❯ mvn test                               
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------< com.fanyfull:demo01 >-------------------------
[INFO] Building demo01 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ demo01 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/fanyfull/edisk/javaCodes/demo01/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ demo01 ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ demo01 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/fanyfull/edisk/javaCodes/demo01/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ demo01 ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:3.2.2:test (default-test) @ demo01 ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.fanyfull.AppTest
fany test
fany test02
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.085 s -- in com.fanyfull.AppTest
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.904 s
[INFO] Finished at: 2023-12-03T11:46:34+08:00
[INFO] ------------------------------------------------------------------------

如果想执行某一个单独的方法,可以这样,

mvn test -Dtest="AppTest#exampleTest02"

如果想执行某一个单独的测试类,也是一样,

mvn test -Dtest="AppTest"

如果我们想在 pom.xml 中去指定想要测试的类的话,那么,可以类似于下面这样,

<!-- to run tests with maven-surefire-plugin -->     
<plugin>                                             
  <groupId>org.apache.maven.plugins</groupId>        
  <artifactId>maven-surefire-plugin</artifactId>     
  <version>3.2.2</version>                           
  <configuration>                                    
    <includes>                                       
      <include>com.fanyfull.AppTest</include>        
      <include>com.fanyfull.AppTest02</include>      
    </includes>                                      
  </configuration>                                   
</plugin>                                            

如果我们想单独制定一个方法的话,那么,可以类似于下面这样,

<plugin>                                             
  <groupId>org.apache.maven.plugins</groupId>        
  <artifactId>maven-surefire-plugin</artifactId>     
  <version>3.2.2</version>                           
  <configuration>                                    
    <test>com.fanyfull.AppTest02#exampleTest02</test>
  </configuration>                                   
</plugin>                                            

如果有了这个声明的话,那么,我们就可以直接执行 mvn test 而不用指定选项了。

完整的 demo 项目,可以在我的 GitHub 找到。

之后我们甚至可以直接把这个 demo clone 下来作为模板,这样就不用用老旧的 maven 自带的模板了。


参考:

1、https://www.baeldung.com/maven-java-main-method
2、https://www.baeldung.com/maven-run-single-test
3、https://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html
4、https://maven.apache.org/surefire/maven-surefire-plugin/index.html


如何使用 maven 在命令行去执行 Java 程序,以及,如何执行测试
http://fanyfull.github.io/2023/12/03/how-to-use-maven-to-execute-Java-programs-in-commandline-and-tests/
作者
Fany Full
发布于
2023年12月3日
许可协议