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:
- to treat a separate directory as a source folder for my test project
- to execute
package
before my plugin - to get the
MavenProject
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>