Java Integration Testing
Java integration testing checks that several real parts of your application work together: your code plus a real database, real files, or a real HTTP connection. Unit tests replace those parts with mocks, so they cannot catch a wrong SQL query, a missing column or a broken file path. Integration tests can.
This lesson shows how to separate integration tests from unit tests with the Maven Failsafe plugin, then tests real files, an H2 database and a local HTTP server. It ends with an enrollment service whose transaction rules are tested against a real database. If JUnit is new to you, start with Java JUnit Basics.
Unit Tests vs Integration Tests in Java
Both kinds of test use JUnit. The difference is what the test touches and how long it takes.
| Unit test | Integration test | |
|---|---|---|
| Scope | One class | Several classes plus real infrastructure |
| Dependencies | Mocks, stubs, fakes | Real database, files, network |
| Speed | Milliseconds | Milliseconds to seconds |
| Finds | Logic bugs | Wiring, SQL, configuration and I/O bugs |
| Maven plugin | Surefire (mvn test) | Failsafe (mvn verify) |
| Naming convention | PriceCalculatorTest | StudentRepositoryIT |
A healthy project has many fast unit tests and fewer, slower integration tests. For the mock-based approach, see Mockito in Java.
Set Up Maven Failsafe for Integration Tests
Maven runs two different plugins for tests:
- Surefire runs classes named
*Test,*Tests,Test*or*TestCasein thetestphase. - Failsafe runs classes named
*IT,IT*or*ITCasein theintegration-testphase, then fails the build in theverifyphase if any of them failed.
Failsafe is not active by default, so you add it to pom.xml:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>6.1.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<!-- In-memory database used only by the integration tests -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.4.240</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.6</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.5.6</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Run the whole build, unit tests first and integration tests second:
mvn verify
Output (shortened):
[INFO] --- surefire:3.5.6:test (default-test) @ course-platform ---
[INFO] Running com.gocourse.reports.PriceCalculatorTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- jar:3.5.0:jar (default-jar) @ course-platform ---
[INFO] --- failsafe:3.5.6:integration-test (default) @ course-platform ---
[INFO] Running com.gocourse.reports.CsvReportWriterIT
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- failsafe:3.5.6:verify (default) @ course-platform ---
[INFO] BUILD SUCCESS
How it works:
- The
junit-bomimport keeps every JUnit artifact on the same version, sojunit-jupiterneeds no<version>. - Surefire runs during
test, before the JAR is packaged. Failsafe runs duringintegration-test, after packaging, so integration tests can use the built application. - Failsafe's
integration-testgoal never fails the build directly. Theverifygoal does, which lets cleanup steps in thepost-integration-testphase still run.
| Command | What runs |
|---|---|
mvn test | Unit tests only |
mvn verify | Unit tests, then integration tests |
mvn verify -DskipITs | Unit tests only, but still packages the project |
mvn verify -Dit.test=StudentRepositoryIT | One integration test class |
mvn verify -DskipTests | Skips both unit and integration tests |
Integration Test With Real Files Using @TempDir
The simplest integration test touches the real file system. JUnit's @TempDir gives each test a fresh temporary folder and deletes it afterwards.
package com.gocourse.reports;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class CsvReportWriter {
public void write(Path file, List<String[]> rows) throws IOException {
List<String> lines = rows.stream()
.map(row -> String.join(",", row))
.toList();
Files.createDirectories(file.getParent()); // create "reports/2026" if missing
Files.write(file, lines);
}
}
package com.gocourse.reports;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class CsvReportWriterIT {
@TempDir
Path tempFolder;
@Test
void writesRowsToANewFolder() throws Exception {
Path reportFile = tempFolder.resolve("reports/2026/november.csv");
List<String[]> rows = List.of(
new String[] {"student", "course", "marks"},
new String[] {"Asha", "Java", "92"},
new String[] {"Ravi", "Python", "78"});
new CsvReportWriter().write(reportFile, rows);
assertTrue(Files.exists(reportFile));
List<String> lines = Files.readAllLines(reportFile);
assertEquals(List.of("student,course,marks", "Asha,Java,92", "Ravi,Python,78"), lines);
lines.forEach(System.out::println);
}
}
Output:
student,course,marks
Asha,Java,92
Ravi,Python,78
How it works:
@TempDirinjects a unique folder per test. Nothing leaks into your project or into other tests.- The test calls the real
FilesAPI, so it proves that missing folders are created and that the line format is right. - A mock could not catch a bug such as forgetting
createDirectories; this test fails withNoSuchFileExceptionif you do.
For more about @TempDir and other setup methods, see JUnit Test Fixtures.
Integration Testing a Database With H2
H2 is a small Java database that can run in memory. Each test creates its own database, runs real SQL against it and throws it away at the end.
package com.gocourse.students;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import javax.sql.DataSource;
public class StudentRepository {
private final DataSource dataSource;
public StudentRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
public void save(String email, String name) throws SQLException {
String sql = "INSERT INTO students (email, name) VALUES (?, ?)";
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, email);
statement.setString(2, name);
statement.executeUpdate();
}
}
public Optional<String> findName(String email) throws SQLException {
String sql = "SELECT name FROM students WHERE email = ?";
try (Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, email);
try (ResultSet resultSet = statement.executeQuery()) {
return resultSet.next() ? Optional.of(resultSet.getString("name")) : Optional.empty();
}
}
}
}
package com.gocourse.students;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.sql.Connection;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import java.util.Optional;
import java.util.UUID;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class StudentRepositoryIT {
private StudentRepository repository;
@BeforeEach
void createFreshDatabase() throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
// A new, uniquely named in-memory database for every test
dataSource.setURL("jdbc:h2:mem:students_" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1");
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("""
CREATE TABLE students (
email VARCHAR(100) PRIMARY KEY,
name VARCHAR(100) NOT NULL
)""");
}
repository = new StudentRepository(dataSource);
}
@Test
void savedStudentCanBeFoundByEmail() throws Exception {
repository.save("asha@example.com", "Asha");
assertEquals(Optional.of("Asha"), repository.findName("asha@example.com"));
assertEquals(Optional.empty(), repository.findName("ravi@example.com"));
}
@Test
void duplicateEmailIsRejectedByTheDatabase() throws Exception {
repository.save("asha@example.com", "Asha");
var error = assertThrows(SQLIntegrityConstraintViolationException.class,
() -> repository.save("asha@example.com", "Asha K"));
System.out.println(error.getClass().getSimpleName());
}
}
Output:
JdbcSQLIntegrityConstraintViolationException
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
jdbc:h2:mem:students_<uuid>creates a private in-memory database.DB_CLOSE_DELAY=-1keeps it alive between connections; without it, H2 drops the database when the last connection closes.- The repository runs its real SQL. A typo in a column name would fail here, while a mocked repository would happily pass.
- The second test proves that the
PRIMARY KEYreally protects against duplicates. H2's exception extends the standardSQLIntegrityConstraintViolationException, so the test does not depend on H2 classes.
Note: H2 is close to standard SQL but is not your production database. For PostgreSQL or MySQL-specific features, many teams run the real database in a Docker container during integration tests with a library such as Testcontainers.
Test an HTTP Client Against a Local Server
Code that calls another service over HTTP should be tested with a real HTTP connection. The JDK includes a small server, com.sun.net.httpserver.HttpServer, that a test can start on a free port.
package com.gocourse.payments;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ExchangeRateClient {
private final HttpClient httpClient = HttpClient.newHttpClient();
private final URI baseUri;
public ExchangeRateClient(URI baseUri) {
this.baseUri = baseUri;
}
/** Returns how many rupees one unit of the given currency is worth. */
public double rupeesPer(String currency) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder(baseUri.resolve("/rates/" + currency)).GET().build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IOException("Rate service returned HTTP " + response.statusCode());
}
return Double.parseDouble(response.body().trim());
}
}
package com.gocourse.payments;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class ExchangeRateClientIT {
static HttpServer server;
static ExchangeRateClient client;
@BeforeAll
static void startServer() throws IOException {
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); // port 0 = any free port
server.createContext("/rates/USD", exchange -> {
byte[] body = "83.25".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
});
server.createContext("/rates/XYZ", exchange -> {
exchange.sendResponseHeaders(404, -1); // -1 = no body
exchange.close();
});
server.start();
int port = server.getAddress().getPort();
client = new ExchangeRateClient(URI.create("http://localhost:" + port));
System.out.println("Test server on port " + port);
}
@AfterAll
static void stopServer() {
server.stop(0);
}
@Test
void parsesTheRateFromARealHttpResponse() throws Exception {
assertEquals(83.25, client.rupeesPer("USD"), 0.0001);
}
@Test
void unknownCurrencyBecomesAnIOException() {
IOException error = assertThrows(IOException.class, () -> client.rupeesPer("XYZ"));
assertEquals("Rate service returned HTTP 404", error.getMessage());
}
}
Output (the port changes on every run):
Test server on port 51734
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
- Port
0asks the operating system for any free port, so the test never clashes with another program. - The client sends a real HTTP request, receives real headers and a body, and parses them. This catches bugs in URL building, status handling and parsing.
@BeforeAlland@AfterAllstart the server once for the class, because starting a server for every test would be slow.
Tag Integration Tests With @Tag
Sometimes integration tests live next to unit tests or do not follow the *IT naming rule. JUnit tags let you select them explicitly.
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("integration")
class ReportExportTest {
@Test
void exportsToRealFolder() {
// ... touches the file system
}
}
Exclude the tag by default through a property, so the command line can change it:
<properties>
<excluded.tags>integration</excluded.tags>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.6</version>
<configuration>
<excludedGroups>${excluded.tags}</excludedGroups>
</configuration>
</plugin>
Run only the tagged tests:
mvn test -Dexcluded.tags= -Dgroups=integration
Output (shortened):
[INFO] Running com.gocourse.reports.ReportExportTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
How it works:
- With no extra options,
mvn testreadsexcluded.tags=integrationand skips every test taggedintegration. -Dexcluded.tags=overrides the property with an empty value, which removes the exclusion for that run.-Dgroups=integrationthen selects only the tagged tests.- The
*ITnaming rule with Failsafe is still the clearest approach. Use tags when you need finer groups such asslowordatabase.
Real-World Example: Java Integration Testing for Course Enrollment
A course platform must never sell more seats than a course has. Enrolling a student inserts an enrollment row and decreases the seat count. Both steps must succeed together or not at all, which is a database transaction. Only an integration test can prove that the rollback really works.
package com.gocourse.enrollment;
public class CourseFullException extends RuntimeException {
public CourseFullException(String courseCode) {
super("Course " + courseCode + " has no seats left");
}
}
package com.gocourse.enrollment;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
public class EnrollmentService {
private final DataSource dataSource;
public EnrollmentService(DataSource dataSource) {
this.dataSource = dataSource;
}
public void enroll(String studentEmail, String courseCode) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false); // start a transaction
try {
if (lockSeatsLeft(connection, courseCode) <= 0) {
throw new CourseFullException(courseCode);
}
try (PreparedStatement update = connection.prepareStatement(
"UPDATE courses SET seats_left = seats_left - 1 WHERE code = ?")) {
update.setString(1, courseCode);
update.executeUpdate();
}
try (PreparedStatement insert = connection.prepareStatement(
"INSERT INTO enrollments (student_email, course_code) VALUES (?, ?)")) {
insert.setString(1, studentEmail);
insert.setString(2, courseCode);
insert.executeUpdate(); // fails on a duplicate enrollment
}
connection.commit();
} catch (SQLException | RuntimeException e) {
connection.rollback(); // undo the seat update as well
throw e;
}
}
}
public int seatsLeft(String courseCode) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
return lockSeatsLeft(connection, courseCode);
}
}
public int enrollmentCount(String courseCode) throws SQLException {
try (Connection connection = dataSource.getConnection();
PreparedStatement select = connection.prepareStatement(
"SELECT COUNT(*) FROM enrollments WHERE course_code = ?")) {
select.setString(1, courseCode);
try (ResultSet resultSet = select.executeQuery()) {
resultSet.next();
return resultSet.getInt(1);
}
}
}
private int lockSeatsLeft(Connection connection, String courseCode) throws SQLException {
try (PreparedStatement select = connection.prepareStatement(
"SELECT seats_left FROM courses WHERE code = ? FOR UPDATE")) {
select.setString(1, courseCode);
try (ResultSet resultSet = select.executeQuery()) {
if (!resultSet.next()) {
throw new IllegalArgumentException("Unknown course: " + courseCode);
}
return resultSet.getInt("seats_left");
}
}
}
}
package com.gocourse.enrollment;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.sql.Connection;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import java.util.UUID;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("EnrollmentService with a real database")
class EnrollmentServiceIT {
private EnrollmentService service;
@BeforeEach
void setUpDatabase() throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:enroll_" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1");
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE courses (code VARCHAR(20) PRIMARY KEY, seats_left INT NOT NULL)");
statement.execute("""
CREATE TABLE enrollments (
student_email VARCHAR(100),
course_code VARCHAR(20) REFERENCES courses(code),
PRIMARY KEY (student_email, course_code)
)""");
statement.execute("INSERT INTO courses VALUES ('JAVA101', 2), ('GO101', 0)");
}
service = new EnrollmentService(dataSource);
}
@Test
@DisplayName("enrolling takes one seat and stores the enrollment")
void enrollTakesASeat() throws Exception {
service.enroll("asha@example.com", "JAVA101");
assertEquals(1, service.seatsLeft("JAVA101"));
assertEquals(1, service.enrollmentCount("JAVA101"));
}
@Test
@DisplayName("a full course rejects the student and changes nothing")
void fullCourseIsRejected() throws Exception {
CourseFullException error = assertThrows(CourseFullException.class,
() -> service.enroll("ravi@example.com", "GO101"));
assertEquals("Course GO101 has no seats left", error.getMessage());
assertEquals(0, service.seatsLeft("GO101"));
assertEquals(0, service.enrollmentCount("GO101"));
}
@Test
@DisplayName("a duplicate enrollment rolls back the seat update")
void duplicateEnrollmentRollsBack() throws Exception {
service.enroll("asha@example.com", "JAVA101");
assertThrows(SQLIntegrityConstraintViolationException.class,
() -> service.enroll("asha@example.com", "JAVA101"));
assertEquals(1, service.seatsLeft("JAVA101")); // still 1, not 0
assertEquals(1, service.enrollmentCount("JAVA101"));
}
}
Run it with:
mvn verify -Dit.test=EnrollmentServiceIT
Output (shortened):
[INFO] --- failsafe:3.5.6:integration-test (default) @ course-platform ---
[INFO] Running com.gocourse.enrollment.EnrollmentServiceIT
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- failsafe:3.5.6:verify (default) @ course-platform ---
[INFO] BUILD SUCCESS
How it works:
- A fresh database per test.
@BeforeEachcreates a uniquely named in-memory database, the two tables and two courses. Every test starts from the same known state, so the tests can run in any order. - The happy path. Enrolling Asha in
JAVA101reduces the seats from 2 to 1 and stores one row. Both are read back with real SQL. - Business rule.
GO101has 0 seats, so the service throwsCourseFullExceptionbefore changing anything. The test confirms that no row was inserted. - The rollback. The seat update runs before the insert. When Asha enrolls twice, the update succeeds but the insert hits the primary key and throws. The
catchblock callsrollback(), so the seat count stays at 1. Remove therollback()line and this test fails withexpected: <1> but was: <0>, a bug no mock-based test would ever show. - Row locking.
SELECT ... FOR UPDATElocks the course row until the transaction ends, so two students cannot take the last seat at the same moment.
The next lesson, Java Code Coverage, shows how to measure which lines and branches these unit and integration tests actually run.