Reputation: 598
I'm developing a custom Maven plugin. For testing, I use JUnit tests with the MojoRule
. The testing itself works fine (I can read the plugin configuration defined in the test pom). However, I want to test access to the project's artifacts.
So far, I haven't figured out how to tell my test class:
package
before my pluginMavenProject
as a field in my class (it's null at runtime)My Mojo class looks like this:
/**
* Identifies potential actions from the project's source code.
*
* @goal identify
*/
public class IdentifyMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}")
private MavenProject project;
@Override
public void execute() {
getLog().info("Project: " + project);
for (Artifact nextArtifact : project.getArtifacts()) {
getLog().info("Next artifact: " + nextArtifact);
}
}
}
The test class looks like this:
public class IdentifyMojoTest {
private static final String TEST_POM_FILE_PATH = "src/test/resources";
private static final String TEST_POM_FILE_NAME = "test-pom.xml";
private MojoRule rule = new MojoRule();
@Ignore("Requires mvn install")
@Test
public void execute_loadWithPlexus_noExceptions() throws Exception {
// Arrange
String goalName = "identify";
File testPom = getTestPom();
// Act
IdentifyMojo identifyMojo = (IdentifyMojo) rule.lookupMojo(goalName, testPom);
identifyMojo.execute();
// Assert
}
@Rule
public MojoRule getRule() {
return rule;
}
@NotNull
@Contract(" -> new")
private File getTestPom() {
return new File(TEST_POM_FILE_PATH, TEST_POM_FILE_NAME);
}
}
The test POM looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<artifactId>test-project</artifactId>
<build>
<plugins>
<plugin>
<groupId>com.example.maven</groupId>
<artifactId>example-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Upvotes: 1
Views: 1328
Reputation: 598
I managed to get the test running by adding this element to the plugin's <configuration>
block:
<project implementation="org.apache.maven.plugin.testing.stubs.MavenProjectStub"/>
This made the Mojo print `Project: MavenProject: null:null:null @ ".
Apparently, the testing harness doesn't provide any default values at all, so I have to inject an instance of MavenProject
in the configuration myself. However, this solves my other problems too, since I don't have to run the package
goal and just have my MavenProjectStub
return some artifacts I built in code.
Source: Unit Testing Maven Mojo - Components and parameters are null
Upvotes: 1