Video in progress
How do you separate unit and integration tests in the build: how do Surefire and Failsafe differ, and when do you need JUnit @Tag?
Surefire runs the fast tests in the test phase, and Failsafe runs the *IT tests in the integration-test and verify phases. Failsafe reports a failure not immediately but in verify, so the post-integration-test cleanup step gets a chance to run. @Tag is for grouping independent of the name pattern.
📖 Answer
The goal of the split is that a developer gets a local mvn test in 30 seconds, while tests that need Docker and a Spring context run in a separate stage.
The usual setup in Maven:
| Surefire | Failsafe | |
|---|---|---|
| Phase | test |
integration-test, verify |
| Default names | *Test, Test*, *Tests, *TestCase |
*IT, IT*, *ITCase |
| On failure | the build stops immediately | the result is checked in verify |
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals><goal>integration-test</goal><goal>verify</goal></goals>
</execution>
</executions>
</plugin>
If the plugin isn't declared inside <plugins> or its goals aren't bound, Failsafe doesn't run at all, and the *IT tests are silently skipped in CI. spring-boot-starter-parent has the executions prepared in pluginManagement, but adding the plugin to <plugins> is still your job; in a project without the parent you write the execution above yourself too.
@Tag is needed when the name pattern isn't enough: for example "slow", "contract", "quarantine". It's convenient to gather it into a meta-annotation:
@Target(TYPE) @Retention(RUNTIME)
@Tag("integration")
@SpringBootTest
@Import(TestContainersConfig.class)
public @interface IntegrationTest { }
Then in Surefire <excludedGroups>integration</excludedGroups>, and in Gradle useJUnitPlatform { excludeTags("integration") } plus a separate integrationTest task.
One catch: the two plugins write separate coverage files. If you don't use JaCoCo's report-aggregate or merge, Sonar sees only the unit test coverage, and code covered by integration tests shows up as "untested".
Sign up to mark studied questions and save your progress.