Best practices for testing

In order to test a plugin, we must create a condition for the plugin execution. In other words, we need one or more test POM files. By using different POM files, we can cover a wide range of test cases and plugin settings.

We can organize the test structure inside the test/resources directory as follows:

Best practices for testing

A testing POM must contain a simple project where we can use our plugin. An example POM file for testing is as follows:

<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.mojo</groupId>
  <artifactId>project-to-test</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>Test MyMojo</name>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
       <artifactId>mantis-maven-plugin</artifactId>
       <version>0.0.1-SNAPSHOT</version>
    <configuration>
       <basedir>
        ${basedir}/src/test/resources/unit/project-to-test
       </basedir>
    <rsName>release_structure.xml</rsName>
    <databaseUrl>http://localhost:8090</databaseUrl>
    <jdbcDriver>com.mysql.jdbc.Driver</jdbcDriver>
    <dbUserName>testName</dbUserName>
    <dbPassword>testPassword</dbPassword>
    <databaseName>mantisIssue</databaseName>
    <projectId>test</projectId>
      </configuration>
    </plugin>
  </plugins>
</build>
</project>

The following code uses the example POM file to access our Mojo as a Java object, and performs some functional tests:

public void testPomAndGoalForNoProperty() throws Exception {
      
File pom = getTestFile( "src/test/resources/unit/project-to-test/pom.xml" );

    assertNotNull( pom );
    assertTrue( pom.exists() );

    MarkResolved myMojo = (MarkResolved) lookupMojo("mark-resolved", pom );

    assertNotNull( myMojo );
    
    myMojo.execute();
    }

First, we get the test POM file, using the getTestFile method. We pass the relative path to the test POM as a parameter.

Subsequently, we exploit the Junit assertion mechanism in order to check whether the test POM exists. We perform the same checks on the Mojo object. We can extract the Mojo from the POM file using the lookupMojo method described earlier.

Finally, we execute the Mojo, invoking its execute method directly. Using different POM files, we can test different plugin goals as different Mojos. In general, it is better to define a test POM for each goal to test.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset