【问题标题】:How to run Python unit test with maven in Java project?如何在 Java 项目中使用 maven 运行 Python 单元测试?
【发布时间】:2021-07-08 13:59:12
【问题描述】:

我有一个主要使用 Java 的项目。 我们在一个包中实现了一些 Python 函数,并希望对它们进行单元测试。这些 .py 文件所在的位置有一个名为 src/python 的包。

我在实施测试时遇到了问题:

  1. 如何确保这些单元测试与 maven 测试框架集成? 那么maven会自动运行它们吗?
  2. 如何让 maven 安装所需的非标准外部 python 库?

感谢您的帮助!

【问题讨论】:

    标签: python maven unit-testing


    【解决方案1】:

    maven-exec-plugin 提供了exec 目标,它可以在 Maven 构建阶段运行任何可执行文件。

    通过将插件配置为在 Maven 的 default lifecycletest 阶段运行,可以安装 Python 包并使用插件执行来执行测试。

    关于您的问题:

    1. Maven 不提供自己的测试框架。它提供了一个称为“测试”的生命周期阶段。在构建 JAR 时,Maven 运行一个默认插件,该插件与 JUnit 等 Java 测试框架(在测试类路径中找到)集成。此外,您可以配置也在“测试”阶段运行的自定义插件执行,但使用 python 做一些事情。

    2. 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-install”和/或“python-test”插件执行的可执行文件或参数。

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2011-09-27
      • 2019-05-05
      • 2021-01-16
      • 2018-02-03
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2015-11-18
      相关资源
      最近更新 更多