如何在java项目中使用maven运行python单元测试?

gr8qqesn  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(536)

我有一个主要使用java的项目。我们在一个包中实现了一些python函数,并希望对它们进行单元测试。这些.py文件位于一个名为src/python的包中。
我必须解决实施测试时遇到的问题:
如何确保这些单元测试与maven测试框架集成?那么maven会自动运行它们吗?
如何让maven安装所需的非标准外部python库?
谢谢你的帮助!

n3ipq98p

n3ipq98p1#

maven exec插件提供了exec目标,可以在maven构建阶段运行任何可执行文件。
通过将插件配置为在maven默认生命周期的测试阶段运行,可以安装python包,并使用插件执行执行测试。
关于你的问题:
maven不提供自己的测试框架。它提供了一个称为“测试”的生命周期阶段。在构建jar时,maven运行一个默认插件,该插件与junit(位于测试类路径上)等java测试框架集成。此外,您还可以配置自定义插件执行,这些执行也可以在“测试”阶段运行,但可以使用python进行一些操作。
python包的安装方式可以与不使用maven时相同。exec目标可用于调用python包管理器可执行文件。
假设:
pip用作python包管理器
“pip”在path环境变量中可用
requirements.txt位于src/python目录中
python测试从“python-m unittest”开始
“python”在path环境变量中可用
在项目的pom.xml中,添加以下插件配置:

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>exec-maven-plugin</artifactId>
      <version>3.0.0</version>
      <executions>
        <execution>
          <id>pip-install</id>
          <phase>test</phase>
          <goals>
            <goal>exec</goal>
          </goals>
          <configuration>
            <workingDirectory>src/python</workingDirectory>
            <executable>pip</executable>
            <arguments>
              <argument>install</argument>
              <argument>-r</argument>
              <argument>requirements.txt</argument>
            </arguments>
          </configuration>
        </execution>

        <execution>
          <id>python-test</id>
          <phase>test</phase>
          <goals>
            <goal>exec</goal>
          </goals>
          <configuration>
            <workingDirectory>src/python</workingDirectory>
            <executable>python</executable>
            <arguments>
              <argument>-m</argument>
              <argument>unittest</argument>
            </arguments>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

如果假设不正确,只需更改“pip安装”和/或“python测试”插件执行的可执行文件或参数。

相关问题