Running JUnit tests in Maven with Surefire Plugin and skipTests in default packaging
Further to the JUnit test we have created, it’s time to have it built into a maven build script so that the test can be run.
Once you have JUnit in your pom.xml file, maven will run tests with JUnit and all valid JUnit test classes under src/test/java directory.
However if you are using more than one test framework such as both TestNG and JUnit, you will need to explicitly specify JUnit as the test provider.
<plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.18.1</version> </dependency> </dependencies> </plugin> [...] </plugins>
For the default maven packaging, you might not want to run test and the tests can be run as a separate job/task.
To address this, all you need to do is create a skipTests property in the pom.xml and have it set to false only when you need to run the tests.
<properties> <skipTests>true</skipTests> </properties>
Use skipTests in the configuration element.
<plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.18.1</version> </dependency> </dependencies> <configuration> <skipTests>${skipTests}</skipTests> </configuration> </plugin> [...] </plugins>
To run the tests:
mvn test -DskipTests=false
Follow me on twitter.
Java, Software
I would suggest we rather run tests by default and switch them off in some extra situations, and not the other way around!
Cheers!
I do agree, but at times we can have a build job purely for compilation and another build job solely to run tests. I had to do it that way, hence this post. 🙂