如何使用JUnit创建Maven插件的自动化测试?

时间:2020-03-06 14:27:29  来源:igfitidea点击:

我已经开发了一个(通常)工作的插件,但是由于其功能与它所处理的项目直接相关,因此如何为该插件开发单元测试和集成测试。我最好的主意是为该插件创建一个集成测试项目,该项目在其生命周期内使用该插件,并具有测试报告该插件在处理数据方面的成功或者失败。

有更好的主意吗?

解决方案

我们需要使用maven-plugin-testing-harness,

<dependency>
        <groupId>org.apache.maven.shared</groupId>
        <artifactId>maven-plugin-testing-harness</artifactId>
        <version>1.1</version>
        <scope>test</scope>
    </dependency>

我们可以从AbstractMojoTestCase派生单元测试类。

我们通常需要在src / test / resources文件夹中创建裸露的POM。

<project>
        <build>
            <plugins>
                <plugin>
                    <groupId>com.mydomain,mytools</groupId>
                    <artifactId>mytool-maven-plugin</artifactId>
                    <configuration>
                        <!-- Insert configuration settings here -->
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>mygoal</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </project>

使用AbstractMojoTest.lookupMojo(String,File)(或者其他变体之一)为特定目标加载Mojo并执行它。

final File testPom = new File(PlexusTestCase.getBasedir(), "/target/test-classes/mytools-plugin-config.xml");
    Mojo mojo = this.lookupMojo("mygoal", testPom);
    // Insert assertions to validate that your plugin was initialised correctly
    mojo.execute();
    // Insert assertions to validate that your plugin behaved as expected

我创建了自己的插件,我们可以参考http://ldap-plugin.btmatthews.com进行澄清,

如果我们想看一些真实的例子,Terracotta Maven插件(tc-maven-plugin)带有一些测试,我们可以在开源伪造中仔细阅读。

该插件位于:http://forge.terracotta.org/releases/projects/tc-maven-plugin/

来源在svn中,网址为:http://svn.terracotta.org/svn/forge/projects/tc-maven-plugin/trunk/

在该资源中,我们可以在以下位置找到一些实际的Maven插件测试:src / test / java / org / terracotta / maven / plugins / tc /