如何从其他模块测试maven插件(Mojo)

时间:2017-04-10 09:01:11

标签: java maven maven-plugin

我正在创建一个maven插件(Mojo)。我已经完成了我的mojo并为它编写了一些测试用例。下一步是创建集成测试。 maven插件是一个更大项目中的模块,已经有一个集成测试模块。

我的问题:有没有办法从其他模块测试maven插件?

我运行集成测试时得到的堆栈跟踪,它位于另一个模块而不是我的maven插件中:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running nl.ciber.webshare.integration.plugin.MavenPluginIT
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
org.apache.maven.plugin.testing.ConfigurationException: Cannot find a configuration element for a plugin with an artifactId of webshare-integration-tests.
        at org.apache.maven.plugin.testing.AbstractMojoTestCase.extractPluginConfiguration(AbstractMojoTestCase.java:619)
        at org.apache.maven.plugin.testing.AbstractMojoTestCase.extractPluginConfiguration(AbstractMojoTestCase.java:582)
        at org.apache.maven.plugin.testing.AbstractMojoTestCase.lookupMojo(AbstractMojoTestCase.java:353)
        at nl.ciber.webshare.integration.plugin.MavenPluginIT.test(MavenPluginIT.java:35)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at junit.framework.TestCase.runTest(TestCase.java:176)
        at junit.framework.TestCase.runBare(TestCase.java:141)
        at junit.framework.TestResult$1.protect(TestResult.java:122)
        at junit.framework.TestResult.runProtected(TestResult.java:142)
        at junit.framework.TestResult.run(TestResult.java:125)
        at junit.framework.TestCase.run(TestCase.java:129)
        at junit.framework.TestSuite.runTest(TestSuite.java:252)
        at junit.framework.TestSuite.run(TestSuite.java:247)
        at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.948 sec <<< FAILURE! - in nl.ciber.webshare.integration.plugin.MavenPluginIT
test(nl.ciber.webshare.integration.plugin.MavenPluginIT)  Time elapsed: 1.793 sec  <<< FAILURE!
java.lang.AssertionError: Cannot find a configuration element for a plugin with an artifactId of webshare-integration-tests.
        at nl.ciber.webshare.integration.plugin.MavenPluginIT.test(MavenPluginIT.java:39)

我的集成测试:

public class MavenPluginIT extends AbstractMojoTestCase {


    @Override
    protected void setUp() throws Exception {
        // TODO Auto-generated method stub
        super.setUp();
    }

    @Override
    protected void tearDown() throws Exception {
        // TODO Auto-generated method stub
        super.tearDown();
    }

    @Test
    public void test() {

        try {
            ClassLoader classLoader = getClass().getClassLoader();
            File pom = new File(classLoader.getResource("simple-sws-plugin/pom.xml").getFile());
            ShareMojo shareMojo = (ShareMojo) lookupMojo("share-file", pom);
            shareMojo.execute();
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }

    }
}

我的设置存根:

public class SettingsStub extends Settings {

    private static final long serialVersionUID = 5812009259225888897L;

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public List getProxies() {
        return Collections.EMPTY_LIST;
    }

    @Override
    public Server getServer(String name) {
        Server server = null;
        if ("webshare".equals(name)) {
            server = new Server();
            server.setPassword("");
        }
        return server;
    }

}

我的项目存根:

public class ShareStub extends MavenProjectStub {
    /**
     * Default constructor
     */


    public ShareStub() {
        MavenXpp3Reader pomReader = new MavenXpp3Reader();
        Model model;
        try {
            model = pomReader.read(ReaderFactory.newXmlReader(new File(getPomdir(), "pom.xml")));
            setModel(model);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        setGroupId(model.getGroupId());
        setArtifactId(model.getArtifactId());
        setVersion(model.getVersion());
        setName(model.getName());
        setUrl(model.getUrl());
        setPackaging(model.getPackaging());

        Build build = new Build();
        build.setFinalName(model.getArtifactId());
        build.setDirectory(getBasedir() + "/target");
        build.setSourceDirectory(getBasedir() + "/src/main/java");
        build.setOutputDirectory(getBasedir() + "/target/classes");
        build.setTestSourceDirectory(getBasedir() + "/src/test/java");
        build.setTestOutputDirectory(getBasedir() + "/target/test-classes");

        model.setBuild(build);

        List compileSourceRoots = new ArrayList();
        compileSourceRoots.add(getBasedir() + "/src/main/java");
        setCompileSourceRoots(compileSourceRoots);

        List testCompileSourceRoots = new ArrayList();
        testCompileSourceRoots.add(getBasedir() + "/src/test/java");
        setTestCompileSourceRoots(testCompileSourceRoots);
    }

    /**
     * {@inheritDoc}
     */
    public File getPomdir() {
        return new File(super.getBasedir() + "/src/test/resources/simple-sws-plugin/");
    }
}

测试项目pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>nl.ciber.webshare.test</groupId>
    <artifactId>test</artifactId>
    <packaging>jar</packaging>
    <version>2.1-SNAPSHOT</version>
    <name>Fake testing pom</name>
    <prerequisites>
        <maven>3.0.3</maven>
    </prerequisites>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>nl.ciber.webshare</groupId>
            <artifactId>webshare-maven-plugin</artifactId>
            <version>2.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <groupId>nl.ciber.webshare</groupId>
                <artifactId>webshare-maven-plugin</artifactId>
                <version>2.1-SNAPSHOT</version>
                <configuration>
                    <settings implementation="nl.ciber.webshare.integration.plugin.Stubs.SettingsStub"/>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>share-file</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

项目结构:

Maven plugin:
├───src
│   ├───main
│   │   └───java
│   │       └───nl
│   │           └───ciber
│   │               └───maven
│   │                   └───plugin
│   │                       │   ShareMojo.java
│   │                       │
│   │                       └───utils
│   │                               GlobUtils.java
│   │                               ZipUtils.java
│   │
│   └───test
│       ├───java
│       │   └───nl
│       │       └───ciber
│       │           └───maven
│       │               └───plugin
│       │                   │   MojoTest.java
│       │                   │
│       │                   └───Stubs
│       │                           SettingsStub.java
│       │                           ShareStub.java
│       │
│       └───resources
│           └───simple-sws-plugin
│                   pom.xml

Integration test:
├───src
│   └───test
│       ├───java
│       │   └───nl
│       │       └───ciber
│       │           └───webshare
│       │               └───integration
│       │                   │
│       │                   └───plugin
│       │                       │   MavenPluginIT.java
│       │                       │
│       │                       └───Stubs
│       │                               SettingsStub.java
│       │                               ShareStub.java
│       │
│       └───resources
│           │   init.sql
│           │   test.txt
│           │   test1.txt
│           │   test2.txt
│           │   test3.txt
│           │
│           └───simple-sws-plugin
│                   pom.xml
│
└─

2 个答案:

答案 0 :(得分:1)

您应该将集成测试放在插件所在的同一模块中。 此外,在较大的项目中使用插件构建不会起作用,因为您使用代码构建插件并尝试将其与此构建一起使用,这意味着您将无法发布插件,这意味着您需要一个稳定的版本可以在你的构建中引用。

最好的方法是将插件与其他项目分开,并在完成测试后在插件项目中进行测试等,您可以发布插件,而不是在项目中使用它。 / p>

我建议您查看其他插件,例如maven-ear-plugin或其他插件,并深入了解maven-invoker-plugin进行集成测试....

如果您使用maven-invoker加mock-repository manger,那么您可以非常好地测试插件。为插件的集成测试创建一个单独的项目永远不是一个好主意......作为一个例子,您可以引用使用模拟存储库管理器等的versions-maven-plugin

答案 1 :(得分:0)

除了maven的不同阶段之外,Mojos应该拥有并且只有具体的逻辑来完成你的自定义工作。在运行任何maven目标时,所有内容都由maven完成/提供,如果我们想测试插件是否正常工作,我们必须启用相同的上下文和环境。

从插件中获取集成测试用例是不对的。但相反,为了确保插件能够完成预期的工作,还需要进行测试。我认为使用仅具有插件集成测试用例的不同模块是件好事。