Unit, integration and end-to-end tests
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A wrong discount, a bad SQL query and a broken URL are three different bugs. Which kind of test finds each one, and how much of ShopLite must that test run?
Unit test: one class, nothing outside it
A unit test checks one class or method on its own: no database, no network, no files. It calls the code with plain values, compares the result and finishes in milliseconds.
This test checks ShopLite's delivery rule and nothing else. It passes plain values in and compares what comes back.
Example 1 · A unit test: delivery charge rules, nothing else
import java.math.BigDecimal;
class DeliveryCharge { static final BigDecimal FREE_FROM = new BigDecimal("499.00"); static final BigDecimal CHARGE = new BigDecimal("40.00");
// Free delivery from Rs 499; otherwise Rs 40 static BigDecimal forSubtotal(BigDecimal subtotal) { return subtotal.compareTo(FREE_FROM) >= 0 ? new BigDecimal("0.00") : CHARGE; }}
public class DeliveryChargeUnitTest { static void check(String name, Object expected, Object actual) { System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name + (expected.equals(actual) ? "" : ": expected " + expected + " but was " + actual)); }
public static void main(String[] args) { // Plain values in, plain values out: no database, no network, no files check("Rs 120 pays delivery", new BigDecimal("40.00"), DeliveryCharge.forSubtotal(new BigDecimal("120.00"))); check("Rs 498.99 pays delivery", new BigDecimal("40.00"), DeliveryCharge.forSubtotal(new BigDecimal("498.99"))); check("Rs 499 is free", new BigDecimal("0.00"), DeliveryCharge.forSubtotal(new BigDecimal("499.00"))); check("Rs 17999 is free", new BigDecimal("0.00"), DeliveryCharge.forSubtotal(new BigDecimal("17999.00"))); }}PASS Rs 120 pays delivery PASS Rs 498.99 pays delivery PASS Rs 499 is free PASS Rs 17999 is free
What this code does
- The test touches only
DeliveryCharge: it passesBigDecimalvalues in and compares what comes back. It runs in milliseconds and needs no set-up. - If one of these fails, the bug can only be inside
forSubtotal, which is why unit test failures are so quick to fix.
Unit tests suit business rules: prices, discounts, delivery charges, validation. When a unit test fails, the problem is almost always inside that one class, so it is quick to find.
Integration test: real pieces working together
An integration test checks that two or more real pieces work together, such as a service with a real database or a controller with real JSON conversion. Nothing that matters is replaced by a stand-in.
Two real pieces run together here: a service and a real file in a temporary folder. A fresh service then reads the same file back.
Example 2 · An integration test: a service and a real file together
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardOpenOption;import java.util.Map;import java.util.TreeMap;
class StockFile { // talks to the real file system private final Path file;
StockFile(Path file) { this.file = file; }
void append(String sku, int stock) throws IOException { Files.writeString(file, sku + "," + stock + "\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND); }
Map<String, Integer> readAll() throws IOException { Map<String, Integer> stock = new TreeMap<>(); if (Files.exists(file)) { for (String line : Files.readAllLines(file)) { String[] parts = line.split(","); stock.put(parts[0], Integer.parseInt(parts[1])); // the last line for a SKU wins } } return stock; }}
class StockService { private final StockFile store;
StockService(StockFile store) { this.store = store; }
void receive(String sku, int quantity) throws IOException { int current = store.readAll().getOrDefault(sku, 0); store.append(sku, current + quantity); }
int stockOf(String sku) throws IOException { return store.readAll().getOrDefault(sku, 0); }}
public class StockIntegrationTest { static void check(String name, Object expected, Object actual) { System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name + (expected.equals(actual) ? "" : ": expected " + expected + " but was " + actual)); }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("shoplite-test"); Path file = dir.resolve("stock.csv"); try { StockService service = new StockService(new StockFile(file)); service.receive("MOB-RN13", 5); service.receive("MOB-RN13", 3); service.receive("ACC-KB100", 30);
// A fresh service reads the same file: the data really reached the disk StockService reopened = new StockService(new StockFile(file)); check("MOB-RN13 after two deliveries", 8, reopened.stockOf("MOB-RN13")); check("ACC-KB100", 30, reopened.stockOf("ACC-KB100")); check("lines in " + file.getFileName(), 3, Files.readAllLines(file).size()); } finally { Files.deleteIfExists(file); Files.deleteIfExists(dir); } }}PASS MOB-RN13 after two deliveries PASS ACC-KB100 PASS lines in stock.csv
What this code does
- Two real pieces run together:
StockServiceandStockFile, writing to a real file in a temporary folder. A bug in either one, or in how they talk (a wrong separator, a lost line), makes a check fail. - Set-up and clean-up are part of an integration test: the test makes its own empty temporary folder and deletes the file at the end, so every run starts the same way.
Example 3 · ShopLite's integration test: OrderService with real MySQL
Runs in: the shoplite-api Spring Boot project (needs the shoplite_test MySQL database)
package com.shoplite.order;
// imports as in the project: AssertJ, JUnit, Spring test, OrderService types
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)class OrderServiceIT {
private static final CurrentUser ADMIN = new CurrentUser(1, null, true);
@Autowired private OrderService orderService;
@Autowired private JdbcClient jdbc;
@Test void placingAnOrderTakesStockAndSavesItemsWithTodaysPrice() { int cleanCodeBefore = stockOf(9);
OrderResponse order = orderService.place(new PlaceOrderRequest(1, 1, List.of( new OrderItemRequest(9, 1), new OrderItemRequest(10, 2))));
assertThat(order.status()).isEqualTo(OrderStatus.PLACED); assertThat(order.total()).isEqualByComparingTo("1799.00"); // 499.00 + 2 x 650.00 assertThat(stockOf(9)).isEqualTo(cleanCodeBefore - 1); assertThat(itemCount(order.id())).isEqualTo(2); }
// ... more tests, and small helpers such as stockOf(id) that read the table with JdbcClient}$ mvn verify ... [INFO] --- failsafe:3.5.6:integration-test (default) @ shoplite-api --- [INFO] Running com.shoplite.order.OrderServiceIT [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.154 s -- in com.shoplite.order.OrderServiceIT
What this code does
@SpringBootTeststarts the real Spring context with the realOrderService, JPA repositories and a real MySQL test database. The test checks the result and then reads the tables to prove stock really went down.- Five tests take about two seconds, far slower than a unit test, but only this kind of test can catch a wrong query or a missing transaction. Its name ends in
IT, so Maven runs it in a separate, later step of the build (the Failsafe plugin), not with the unit tests.
Integration tests catch the bugs that live between pieces: a wrong column name, a missing transaction, a date stored in the wrong format.
They are slower, because they start real things, and they need set-up such as a test database.
End-to-end test: the whole app through its real interface
An end-to-end test starts the whole application and uses it from outside, through its real interface. For ShopLite that is the HTTP API: real requests to real URLs, checking status codes and JSON.
This test starts a small real HTTP server and calls it with Java's HttpClient, the way a client app would. The last check shows a wrong URL.
Example 4 · An end-to-end test over real HTTP
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
public class ProductApiEndToEndTest { // A tiny stand-in for the ShopLite app: one real HTTP server with one route static HttpServer startApp() throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); server.createContext("/api/v1/products/", exchange -> { String id = exchange.getRequestURI().getPath().substring("/api/v1/products/".length()); boolean found = id.equals("1"); String json = found ? "{\"id\":1,\"sku\":\"MOB-RN13\",\"price\":17999.00}" : "{\"title\":\"Not Found\",\"status\":404}"; byte[] body = json.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", found ? "application/json" : "application/problem+json"); exchange.sendResponseHeaders(found ? 200 : 404, body.length); exchange.getResponseBody().write(body); exchange.close(); }); server.start(); return server; }
static void check(String name, Object expected, Object actual) { System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name + (expected.equals(actual) ? "" : ": expected " + expected + " but was " + actual)); }
public static void main(String[] args) throws Exception { HttpServer app = startApp(); String base = "http://localhost:" + app.getAddress().getPort(); // a free port picked at start HttpClient http = HttpClient.newHttpClient(); try { HttpResponse<String> ok = http.send(HttpRequest.newBuilder(URI.create(base + "/api/v1/products/1")).build(), HttpResponse.BodyHandlers.ofString()); check("GET product 1 is 200", 200, ok.statusCode()); check("body has the SKU", true, ok.body().contains("\"sku\":\"MOB-RN13\""));
HttpResponse<String> missing = http.send(HttpRequest.newBuilder(URI.create(base + "/api/v1/products/999")).build(), HttpResponse.BodyHandlers.ofString()); check("GET product 999 is 404", 404, missing.statusCode());
HttpResponse<String> typo = http.send(HttpRequest.newBuilder(URI.create(base + "/api/v1/product/1")).build(), HttpResponse.BodyHandlers.ofString()); check("a client using /product/1 gets 200", 200, typo.statusCode()); } finally { app.stop(0); } }}PASS GET product 1 is 200 PASS body has the SKU PASS GET product 999 is 404 FAIL a client using /product/1 gets 200: expected 200 but was 404
What this code does
- The test starts a real HTTP server on a free port and talks to it with Java's
HttpClient, exactly as a client app would: real URLs, real status codes, real JSON text. - The last check shows the bug only this level can see: a client calling
/api/v1/product/1(nos) gets 404. No unit test of the pricing or product code would ever notice a wrong URL.
Example 5 · ShopLite's end-to-end smoke test
Runs in: the shoplite-api Spring Boot project (needs the shoplite_test MySQL database)
package com.shoplite;
// imports: AssertJ, JUnit, java.net.http, Spring Boot test annotations
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)class ShopliteApiSmokeIT {
@LocalServerPort private int port;
private final HttpClient http = HttpClient.newHttpClient();
@Test void readsAProductFromMySql() throws Exception { HttpResponse<String> response = get("/api/v1/products/1");
assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body()).contains("\"sku\":\"MOB-RN13\"", "\"price\":17999.00"); }
private HttpResponse<String> get(String path) throws Exception { HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)).build(); return http.send(request, HttpResponse.BodyHandlers.ofString()); }}[INFO] Running com.shoplite.ShopliteApiSmokeIT [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.171 s -- in com.shoplite.ShopliteApiSmokeIT
What this code does
RANDOM_PORTstarts the full ShopLite app with Tomcat on a free port; the test then uses plain HTTP, so URL mapping, security rules, JSON and MySQL are all in the path.- Three requests take about three seconds. That is fine for a handful of tests that prove the system starts and answers, but far too slow for hundreds of rule checks.
An end-to-end test proves that everything is wired together: URL mappings, security, JSON, services and database.
It is the slowest kind and, when it fails, it only tells you that something somewhere in the chain is wrong.
Order of execution
Follow one request
Put the steps in the order ShopLite handles GET /api/v1/products/1.
Which ShopLite bug each kind catches
Ask "where can this bug live?" and write the smallest test that reaches that place.
Each kind of test is best at a different kind of bug:
- A wrong discount (10% given at 9 items instead of 10): pure logic in one class, so a unit test catches it in milliseconds.
- A bad SQL query (stock reduced for the wrong product id, a misspelt column): only a real database shows it, so it needs an integration test.
- A broken URL (
/api/v1/product/1instead of/products/1, or a security rule that blocks a public page): only the running app shows it, so it needs an end-to-end test.
A unit test with a stand-in database can never find the SQL bug, and an E2E test is a slow way to find the discount bug.
Predict the output
Which test catches this bug?
Pick the smallest kind of test that can find the bug.
Round 1 of 3
Free delivery should start at Rs 499. Which test catches this bug?
Speed, cost and confidence trade-offs
A fragile test can fail for reasons unrelated to your change, such as a busy database or a changed message. The more of the app a test runs, the more fragile it tends to be.
The more of the app a test runs, the more confidence it gives that the real system works, but the slower and more fragile it is.
The three kinds compare like this:
- Unit: milliseconds, no set-up, points to the exact class; says nothing about wiring.
- Integration: around a second or more per test class, needs a test database; proves SQL and mapping.
- End-to-end: seconds, needs the whole app; proves the system works, but failures are vague.
A healthy project uses all three, with most tests at the fast, cheap end. The next lesson turns this into the test pyramid.
Next step
Check your understanding
11 quick questions