使用存储库进行测试

注意:此示例改进了用于测试存储库的说明书。

在开发 Maven 插件时,您经常需要使用存储库。假设 MyMojo 需要将工件下载到您的本地存储库中,即:

public class MyMojo
    extends AbstractMojo
{
    /**
     * Used for resolving artifacts
     */
    @Component
    private ArtifactResolver resolver;

    /**
     * Factory for creating artifact objects
     */
    @Component
    private ArtifactFactory factory;

    /**
     * Local Repository.
     */
    @Parameter( defaultValue = "${localRepository}", readonly = true, required = true )
    private ArtifactRepository localRepository;

    public void execute()
        throws MojoExecutionException
    {
        ...

        Artifact artifact = factory.createArtifact( "junit", "junit", "3.8.1", "compile", "jar" );
        try
        {
            resolver.resolve( artifact, project.getRemoteArtifactRepositories(), localRepository );
        }
        catch ( ArtifactResolutionException e )
        {
            throw new MojoExecutionException( "Unable to resolve artifact:" + artifact, e );
        }
        catch ( ArtifactNotFoundException e )
        {
            throw new MojoExecutionException( "Unable to find artifact:" + artifact, e );
        }

        ...
     }
}

创建存根

测试项目的存根:

public class MyProjectStub
    extends MavenProjectStub
{
    /**
     * Default constructor
     */
    public MyProjectStub()
    {
        ...
    }

    /** {@inheritDoc} */
    public List getRemoteArtifactRepositories()
    {
        ArtifactRepository repository = new DefaultArtifactRepository( "central", "http://repo.maven.apache.org/maven2",
                                                                       new DefaultRepositoryLayout() );

        return Collections.singletonList( repository );
    }
}

配置项目到测试的pom

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-my-plugin</artifactId>
        <configuration>
          <!-- Specify where this pom will output files -->
          <outputDirectory>${basedir}/target/test-harness/project-to-test</outputDirectory>

          <!-- By default <<<${basedir}/target/local-repo", where basedir refers
               to the basedir of maven-my-plugin. -->
          <localRepository>${localRepository}</localRepository>
          <!-- The defined stub -->
          <project implementation="org.apache.maven.plugin.my.stubs.MyProjectStub"/>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

执行测试

调用mvn test将创建${basedir}/target/local-repo/junitjunit/3.8.1/junit-3.8.1.jar文件。