Blake Caldwell: /dev/blog
Not a Java Developer

Conditionally Run JUnit Integration Tests with Spring

Ideally, your unit test suites require no external dependencies - those should be mocked out. However, sometimes you want extra assurance that your code works with live endpoints via integration tests.

For example, you might want to make sure that your code can successfully navigate your corporate proxy and firewall to make external web requests. For this, we’ll write tests that only run when a command line parameter is defined.

This demonstration assumes that you’re using Spring’s JUnit Runner and Maven for running your tests. The @IfProfileValue annotation will tell the test runner to only include this test suite if our configured ProfileValueSource returns “true” for “live-external-tests-enabled”.

package org.blakecaldwell;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.IfProfileValue;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@IfProfileValue(name="live-external-tests-enabled", value="true")
public class IntegrationTest
    public void testExternalConnection()
    {"testExternalConnection failed!");

Let’s verify that this test suite is ignored by default with the maven command:

mvn test

You’ll see that you now have a skipped test:


Tests run: 1337, Failures: 0, Errors: 0, Skipped: 1

Now, try it again, but this time with our test included:

mvn test -Dlive-external-tests-enabled=true

You’ll now see that the test was run:

Results :

Tests in error: 
  testExternalConnection(org.blakecaldwell.IntegrationTest): Failed to load ApplicationContext

Tests run: 1337, Failures: 0, Errors: 1, Skipped: 0

The @IfProfileValue annotation can also be used above an individual test.