Maven Surefire + Failsafe, the easiest way

Tell me I’m not the only one. Your web application has a bunch of unit tests, and Cobertura says all kinds of nice things about your coverage. But every now and then you check something in and the build breaks. But it worked locally, so what the hell?

mavenThen you realize that one of the tests depends on a REST call to some other system, and they changed their data. In other words, you realize that you, my friend, have a mix of unit tests and integration tests.

Don’t panic. Just add the Maven Failsafe plugin to your build. Failsafe is similar to the default testing plugin that you already know and love: Surefire. But it’s specifically made to run integration tests. There’s a lot of great documentation, but I hope this example will get you up and running faster than I did.

Step one: add the Failsafe plugin to your pom

[code lang=”xml”]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.17</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
[/code]

Unfortunately, the Failsafe plugin doesn’t come out of the box like Surefire does so you have to explicitly add it to your build.

Step two: separate your unit and integration tests by convention

By default, the Surefire plugin will pick up any classes named *Test.java or *TestCase.java. By contrast, Failsafe picks up any classes named *IT.java. That’s nice because you can let them coexist in the same src/test/java folder.

src-test

Just for reference, here’s my “code” for the Demo tests:

[code lang=”java”]
public class DemoTest {
@Test
public void test() {
System.out.println("Hi. I’m a unit test.");
}
}
[/code]

 

[code lang=”java”]
public class DemoIT {
@Test
public void test() {
System.out.println("And I’m an integration test. Can’t you tell?");
}
}
[/code]

Step three: run mvn verify and check the output

The verify life cycle runs both test and the integration tests (check the documentation for a lot of important detail):

mvn-verify

You’ll see it run the normal unit tests:

demotest

And then it runs again for the integration tests:

demoit

As to how you’re going to integrate this life cycle into Jenkins, Bamboo, or whatever — I’ll leave that up to you! Good luck out there and let me know how it goes.

Leave a Reply

Your email address will not be published. Required fields are marked *