首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未扩展的GMavenPlus Groovy project.basedir单元测试

未扩展的GMavenPlus Groovy project.basedir单元测试
EN

Stack Overflow用户
提问于 2015-06-15 15:31:06
回答 2查看 866关注 0票数 0

我目前正试图用GMavenPlus编写一个Maven插件(谢谢@Keegan!)和Groovy 2.4.3。简单地说,这个插件解析了一个SQL SQL目录,并从那些解析的SQL中生成输出。

当构建、导入并在一个完整的消费项目中运行时,本身工作得很好。霍拉!

问题在于单元测试。当尝试对这个Mojo进行单元测试时,像${project.basedir}这样的Maven POM没有被扩展,因此这个mojo出现了一个错误,比如“文件未找到!${project.basedir}/src/ test /resources/ddl”。从该错误消息中可以看到,${project.basedir}是作为文字传递的,而不是被展开的。

我目前正在使用Maven插件测试Harness (使用固定的依赖项,请参阅这个博客)、JUnit 4.12和AssertJ 3.0.0作为测试堆栈。

有什么想法或具体的技巧可以让project.basedir这样的东西在单元测试中扩展吗?

提前感谢!

有问题的单元测试:

代码语言:javascript
复制
import edge.SqlToScalaMojo
import org.junit.Before
import org.junit.Test

/**
 * Created by medge on 6/15/15.
 */
class SqlToScalaMojoTest extends BaseMojoTest<SqlToScalaMojo> {

    SqlToScalaMojo mojo

    @Before
    void setup() {
        mojo = getMojo("parse-ddls")
    }

    @Test
    void testMojoExecution() throws Exception {
        assertThat mojo isNotNull()

        mojo.execute()
    }
}

BaseMojoTest.groovy (实际上只是一个方便的基类):

代码语言:javascript
复制
import org.apache.maven.plugin.AbstractMojo
import org.apache.maven.plugin.testing.MojoRule
import org.junit.Rule

/**
 * Base Test class for Mojo tests. Extends {@link org.assertj.core.api.Assertions}
 *
 * If a type is given to this class then the result of #getMojo() does not have to be cast, reducing the amount of code
 * to be written in the unit tests themselves.
 *
 * Created by medge on 6/5/15.
 */
abstract class BaseMojoTest<T extends AbstractMojo> extends org.assertj.core.api.Assertions {

    /**
     * MojoRule used to lookup Mojos
     */
    @Rule public MojoRule rule = new MojoRule()

    /**
     * Get a configured mojo using the default pom file. Calls #getMojo(goal, getPom()) implicitly
     *
     * @param goal Goal to look up
     * @return T configured Mojo
     */
    T getMojo(String goal) {
        getMojo(goal, getPom())
    }

    /**
     * Get a configured mojo using the specified pom file
     *
     * @param goal Goal to look up
     * @param pom POM file to use when configuring Mojo
     * @return T configured Mojo
     */
    T getMojo(String goal, File pom) {
        T mojo = (T) rule.lookupMojo(goal, pom)

        mojo
    }

    /**
     * Default POM file if no custom path is given
     */
    String defaultPomPath = "src/test/resources/plugin-config.xml"

    /**
     * Return a File reference containing the default POM file
     *
     * @return File
     */
    File getPom() {
        getPom(defaultPomPath)
    }

    /**
     * Return a File reference containing the POM file found at the specified path. Implicitly asserts that the POM
     * exists using <code>assertFile</code>
     *
     * @param path Path to user-defined POM (overrides the default if provided)
     * @return File containing the specified POM.
     */
    File getPom(String path) {
        File _pom = getTestFile(path)

        // Implicitly assert POM exists
        assertFile(_pom)

        // Then return the POM file
        _pom
    }

    /**
     * Convenience method to assert that a file is valid
     *
     * @param file File to validate
     */
    static void assertFile(File file) {
        assertThat file isNotNull()
        assertThat file exists()
    }

    /**
     * Get the current project's base directory. From {@link org.codehaus.plexus.PlexusTestCase}
     *
     * @return Base directory path
     */
    static String getBaseDir() {
        final String path = System.getProperty( "basedir" );

        path ?: new File( "" ).getAbsolutePath();
    }

    /**
     * Return a test file from the src/test/resources directory. Assumes the base directory is src/test/resources so the
     * src/test/resources prefix can be omitted from the path if desired
     *
     * @param path File path
     * @return File
     */
    static File getTestFile(String path) {
        File testFile

        if(path.indexOf("src/test/resources/") > -1)
            testFile = getTestFile(getBaseDir(), path)
        else
            testFile = getTestFile(getBaseDir(), "src/test/resources/${path}")

        testFile
    }

    /**
     * Retrieve a test file from the given baseDir/path
     *
     * @param baseDir String base directory to look in
     * @param path String path to the file desired
     * @return File
     */
    static File getTestFile(String baseDir, String path) {
        new File(baseDir, path)
    }
}

Mojo本身的主POM文件:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>edge</groupId>
    <artifactId>parser-mojo</artifactId>
    <version>0.0.3-SNAPSHOT</version>
    <packaging>maven-plugin</packaging>

    <properties>
        <groovy.version>2.4.3</groovy.version>
        <maven.version>3.3.3</maven.version>
        <junit.version>4.12</junit.version>
        <assertj.version>3.0.0</assertj.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>${groovy.version}</version>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${assertj.version}</version>
            <scope>test</scope>
        </dependency>


        <!-- Dependencies for Maven Mojos -->
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-utils</artifactId>
            <version>3.0.22</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>${maven.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-artifact</artifactId>
            <version>${maven.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-compat</artifactId>
            <version>${maven.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>${maven.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugin-testing</groupId>
            <artifactId>maven-plugin-testing-harness</artifactId>
            <version>3.3.0</version>
            <scope>test</scope>
            <type>jar</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.gmavenplus</groupId>
                <artifactId>gmavenplus-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>addSources</goal>
                            <goal>addTestSources</goal>
                            <goal>generateStubs</goal>
                            <goal>compile</goal>
                            <goal>testGenerateStubs</goal>
                            <goal>testCompile</goal>
                            <goal>removeStubs</goal>
                            <goal>removeTestStubs</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.4</version>
                <configuration>
                    <!-- see http://jira.codehaus.org/browse/MNG-5346 -->
                    <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
                </configuration>
                <executions>
                    <execution>
                        <id>generate-descriptor</id>
                        <goals>
                            <goal>descriptor</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>help-goal</id>
                        <goals>
                            <goal>helpmojo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

单元测试期间使用的测试POM:

代码语言:javascript
复制
<project>
    <build>
        <plugins>
            <plugin>
                <groupId>edge</groupId>
                <artifactId>parser-mojo</artifactId>
                <version>0.0.3-SNAPSHOT</version>
                <configuration>
                    <template>${project.basedir}/src/test/resources/sample.template</template>
                    <inputDir>${project.basedir}/src/test/resources/ddl</inputDir>
                    <outputDir>${project.basedir}/src/test/resources/generated/</outputDir>
                </configuration>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>parse-ddls</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-23 23:27:41

找到了我自己问题的答案。张贴在这里,以防其他人正在寻找同样的问题。

首先,在@Parameter注释方面,我遇到了与Mojo本身有关的另一个问题。以下内容如下:

代码语言:javascript
复制
@Parameter(defaultValue = "${project.basedir}/src/main/resources")
String inputDir

将生成一个错误,因为Groovy编译器将在Maven之前获取字符串"${project.basedir}/src/main/resources"。然后,它将执行其计算,并将其转换为GString。这会生成一个错误,因为注释需要一个java.lang.String,但它将得到java.lang.Object

正如@Keegan在另一个问题中指出的,解决方案是使用单引号而不是双引号:

代码语言:javascript
复制
@Parameter(defaultValue = '${project.basedir}/src/main/resources')
String inputDir

Groovy编译器不会计算字符串,Maven将从中提取

接下来,在单元测试期间,没有读取有关defaultValue的原始问题。罪魁祸首是BaseMojoTest.groovy中的这种方法:

代码语言:javascript
复制
T getMojo(String goal, File pom) {
    T mojo = (T) rule.lookupMojo(goal, pom)

    mojo
}

具体而言,本部分:

代码语言:javascript
复制
rule.lookupMojo(goal, pom)

lookupMojo在MojoRule 上不计算参数注释的默认值。它希望测试POM文件中存在所有可能的参数。快速浏览了一下MojoRule的源代码,我找到了一种修复它的方法:

代码语言:javascript
复制
/**
 * Get a configured mojo using the specified pom file
 *
 * @param goal Goal to look up
 * @param pom POM file to use when configuring Mojo
 * @return T configured Mojo
 */
T getMojo(String goal, File pom) {
    T mojo = (T) rule.lookupConfiguredMojo(getMavenProject(pom), goal)

    mojo
}

/**
 * Method to handle creating a MavenProject instance to create configured Mojos from
 * @param pom File to POM file containing Mojo config
 * @return MavenProject
 */
MavenProject getMavenProject(File pom) {
    // create the MavenProject from the pom.xml file
    MavenExecutionRequest request = new DefaultMavenExecutionRequest()
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest()
            .setRepositorySession(new DefaultRepositorySystemSession())
    MavenProject project = rule.lookup(ProjectBuilder.class).build(pom, configuration).getProject()

    project.basedir = new File(getBaseDir())

    // Implicit assert
    assertThat project isNotNull()

    // And return
    project
}

getMavenProject()方法与MojoRule#readMavenProject()中的代码略有不同,修改后的代码引用了MojoRule和我对getBaseDir()的定义。由该方法生成的Mojos现在正确地评估@Parameter的defaultValue!我确实觉得getMavenProject()可能会变得更有效率(而不是每次创建一个MavenProject ),但是现在已经足够了。

还有一件事

您可能已经注意到getMavenProject()方法中的这一行:

代码语言:javascript
复制
project.basedir = new File(getBaseDir())

这个非常恼人的小黑客是必要的,因为在创建MavenProject对象时:

代码语言:javascript
复制
MavenProject project = rule.lookup(ProjectBuilder.class).build(pom, configuration).getProject()

${project.basedir}实际上成为的基础,这是单元测试中使用的测试POM文件。如果像我一样,在src/ test /resources中有一个测试POM,那么basedir将成为类似于/Users/medge/.../src/test/resources.的东西。因此,当展开${project.basedir}的@参数注释时,例如:

代码语言:javascript
复制
@Parameter(defaultValue='${project.basedir}/src/main/resources')
String inputDir

当从单元测试运行时,inputDir将解析为/Users/medge/.../src/test/resources/src/main/resources

微妙的事情会把你绊倒..。

希望这对其他人有帮助!

票数 2
EN

Stack Overflow用户

发布于 2016-10-04 12:41:25

我有一个类似的问题,但我插入路径从配置和发现不同的解决方案。

我将测试项目pom更改为:

代码语言:javascript
复制
<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>com.example.maven.plugin.MyPlugin</groupId>
    <artifactId>testProject</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Test MyPlugin</name>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>myPlugin-maven-plugin</artifactId>
                <configuration>
                    <testDirectory>${basedir}\src\test\resources\testDir</testDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

不同之处在于testDirectory。而

<testDirectory>${project.basedir}\src\test\resources\testDir</testDirectory>

计算结果为相同的字符串,

<testDirectory>${basedir}\src\test\resources\testDir</testDirectory>

计算结果为文件系统C:\Development\projects\..\src\test\resources\testDir上的具体路径。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30849141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档