Testing in Maven

Another important point in the work of Maven is the testing phase. It will be executed if you run test , package , verify or any other phase that comes after them.

By default, Maven will run all tests that are in the src/test/java/ folder . To distinguish tests to be run from other java files, a naming convention has been adopted. Tests are java classes whose names start with "Test" and end with "Test" or "TestCase" .

General pattern of test names:

  • **/Test*.java
  • **/*Test.java
  • **/*TestCase.java

These tests must be written based on the Junit or TestNG test framework. These are very cool frameworks, we will definitely talk about them a little later.

Test results in the form of reports in .txt and .xml formats are saved in the ${basedir}/target/surefire-reports directory.

Test setup

There are usually a lot of options for running tests, so the Maven developers have made a special plugin, in the parameters for which you can set all the detailed information on testing. The plugin is called Maven Surefire Plugin and is available at .

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
    	<version>2.12.4</version>
    	<configuration>
        	<includes>
                <include>Sample.java</include>
        	</includes>
    	</configuration>
	</plugin>
</plugins>

In the example, we told the plugin that it needs to run a single test class, Sample.java.

How to quickly eliminate broken tests

To run the project for testing, you need to run the mvn test command. But more often there is a need to exclude some tests from testing. For example, they may be broken, take too long to run, or for any other reason.

First, you can simply tell Maven to skip the tests when doing the build phase. Example:

mvn clean package -Dmaven.test.skip=true

Secondly, in the plugin configuration, you can disable the execution of tests:


<configuration>
    <skipTests>true</skipTests>
</configuration>

And thirdly, tests can be excluded using the <exclude> tag . Example:


<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
    	<version>2.12.4</version>
    	<configuration>
        	<excludes>
           	<exclude>**/TestFirst.java</exclude>
	           <exclude>**/TestSecond.java</exclude>
    	</excludes>
    	</configuration>
    </plugin>
</plugins>