如何使用 JUnit4 测试 Maven 插件

Bet*_*ide 5 java junit4 maven-plugin maven

我正在编写一个 Maven 插件,并想编写一些 JUnit 测试。我按照Maven 插件测试中的描述进行操作。不幸的是,在我可以配置或调用任何内容之前,我在测试设置期间不断收到异常。

这是我的 JUnit 测试代码:

public class ResetMojoTest {

    private static final String POM_FILE_NAME = "/path/to/pom.xml"; 

    @Rule
    public MojoRule rule = new MojoRule();

    @Test
    public void testSomething()
        throws Exception
    {
        File pom = new File(POM_FILE_NAME);
        Assert.assertNotNull( pom );
        Assert.assertTrue( pom.exists() );

        ResetMojo resetMojo = (ResetMojo) rule.lookupMojo( "touch", pom );
        Assert.assertNotNull( resetMojo );
        resetMojo.execute();
    }

}
Run Code Online (Sandbox Code Playgroud)

这是异常的堆栈跟踪:

java.io.IOException: Stream closed
    at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:134)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
    at org.apache.commons.io.input.BOMInputStream.getBOM(BOMInputStream.java:175)
    at org.apache.commons.io.input.BOMInputStream.getBOMCharsetName(BOMInputStream.java:201)
    at org.apache.commons.io.input.XmlStreamReader.doRawStream(XmlStreamReader.java:412)
    at org.apache.commons.io.input.XmlStreamReader.<init>(XmlStreamReader.java:206)
    at org.apache.commons.io.input.XmlStreamReader.<init>(XmlStreamReader.java:171)
    at org.apache.commons.io.input.XmlStreamReader.<init>(XmlStreamReader.java:140)
    at org.apache.maven.plugin.testing.AbstractMojoTestCase.setUp(AbstractMojoTestCase.java:119)
    at org.apache.maven.plugin.testing.MojoRule$2.evaluate(MojoRule.java:299)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
Run Code Online (Sandbox Code Playgroud)

关于如何让它发挥作用有什么想法吗?

khm*_*ise -1

POM文件的加载看起来不太好:

以下代码来自示例:

File pom = rule.getTestFile( "src/test/resources/unit/project-to-test/pom.xml" );
Run Code Online (Sandbox Code Playgroud)

这就是你所拥有的:

File pom = new File(POM_FILE_NAME);
Run Code Online (Sandbox Code Playgroud)

除此之外,您还有一个不同的位置,如下所示:

private static final String POM_FILE_NAME = "/path/to/pom.xml"; 
Run Code Online (Sandbox Code Playgroud)

但pom文件的位置应该是:

private static final String POM_FILE_NAME = "src/test/resources/pom.xml"; 
Run Code Online (Sandbox Code Playgroud)

  • [MojoRule 类](http://maven.apache.org/plugin-testing/maven-plugin-testing-harness/apidocs/org/apache/maven/plugin/testing/MojoRule 上不存在方法 `getTestFile` .html)。甚至有一个[bug](http://jira.codehaus.org/browse/MPLUGINTESTING-34)指出示例文档是错误的。 (5认同)