Test data and test profiles
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite test that runs on your dev database can wipe your own data, and a test that depends on another test's rows fails at random. How do tests get safe, repeatable data?
@ActiveProfiles("test") and application-test.properties
A profile is a named set of settings. Spring loads application-<profile>.properties on top of application.properties, so the test profile can point every test at its own database.
Point every test at its own database with one annotation and one file. Example 1 is application-test.properties; Example 2 shows what goes wrong when the annotation is forgotten.
Example 1 · src/test/resources/application-test.properties
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
# src/test/resources/application-test.properties# Integration tests (*IT) use their own database, never your dev data.spring.datasource.url=${TEST_DB_URL:jdbc:mysql://localhost:3306/shoplite_test}spring.datasource.username=${DB_USER:root}spring.datasource.password=${DB_PASSWORD:}# Only the schema: no dev-data seed rows. Each IT loads its rows with @Sql.spring.flyway.locations=classpath:db/migrationlogging.level.com.shoplite=INFO# A key for tests only: it signs nothing outside the test run (32 bytes, Base64)shoplite.jwt.secret=dGVzdC1vbmx5LWtleS1uZXZlci11c2VkLWluLXByb2Q=shoplite.cors.allowed-origins=http://localhost:3000INFO com.shoplite.order.OrderOwnershipIT : The following 1 profile is active: "test" INFO com.zaxxer.hikari.HikariDataSource : ShopLitePool - Starting... INFO com.zaxxer.hikari.pool.HikariPool : ShopLitePool - Added connection com.mysql.cj.jdbc.ConnectionImpl@3c0e00a8 INFO o.f.core.internal.command.DbValidate : Successfully validated 5 migrations (execution time 00:00.031s) INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite_test`: 5
What this code does
${TEST_DB_URL:...}reads the environment variable and falls back to the localshoplite_testdatabase; there is noDB_URLin this file.- Only
db/migrationis loaded, so the test schema has no dev rows; each IT class loads the seed rows it needs with@Sql. - The log line "The following 1 profile is active: \"test\"" is the first thing to check when a test touches the wrong data.
Example 2 · Forgetting @ActiveProfiles("test")
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
@SpringBootTest@AutoConfigureMockMvc// forgot: @ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)class CategoryFlowIT { ...}INFO com.shoplite.category.CategoryFlowIT : No active profile set, falling back to 1 default profile: "dev" INFO o.f.core.internal.command.DbMigrate : Current version of schema `shoplite`: 5.1 ... Then @Sql runs reset-test-db.sql against `shoplite`: every TRUNCATE empties a table of your dev data.
What this code does
- No profile is set, so Spring uses
spring.profiles.default=dev: the dev URL and the dev databaseshoplite. - The test context starts happily, then
@Sqlruns the reset script on your dev data. - Section 4 adds a guard that stops this; the first line of defence is the annotation on every IT class.
@ActiveProfiles("test") on a test class turns on the test profile, so src/test/resources/application-test.properties decides the database, the JWT secret and the log levels. ShopLite's test file reads TEST_DB_URL with a default of jdbc:mysql://localhost:3306/shoplite_test, loads only the schema migrations, and never reads DB_URL, so a test can never pick up the dev or production URL from your environment.
The trap: ShopLite's application.properties says spring.profiles.default=dev. A full test without @ActiveProfiles("test") quietly runs with dev, on your dev database.
Predict the output
Which database is used?
Read the test set-up and pick the database the test connects to.
Round 1 of 3
Which database does it use?
@Sql scripts and test-data builders
@Sql is a Spring test annotation that runs SQL scripts or statements around a test. executionPhase picks the moment: before or after each method (the default is before), or once before or after the class.
Give each test the rows it needs. Example 3 loads the seed rows with @Sql; Example 4 builds test objects with defaults, so a test says only what matters to it.
Example 3 · src/test/java/com/shoplite/category/CategoryDeleteIT.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
package com.shoplite.category;
@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS) // seed rows once@Transactionalclass CategoryDeleteIT {
@Autowired private MockMvcTester mvc;
@Test @WithMockUser(roles = "ADMIN") @Sql(statements = "INSERT INTO categories (name, parent_id) VALUES ('Empty Shelf Test', NULL)") void anEmptyCategoryCanBeDeleted() { // the statement ran inside this test's transaction: the new row is id 8 and is rolled back afterwards assertThat(mvc.delete().uri("/api/v1/categories/8")).hasStatus(HttpStatus.NO_CONTENT); }
@Test @WithMockUser(roles = "ADMIN") void aCategoryWithProductsCannotBeDeleted() { assertThat(mvc.delete().uri("/api/v1/categories/7")) .hasStatus(HttpStatus.CONFLICT) .bodyJson().extractingPath("$.detail").isEqualTo("Category 7 has products and cannot be deleted."); }}[INFO] Running com.shoplite.category.CategoryDeleteIT [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.512 s -- in com.shoplite.category.CategoryDeleteIT
What this code does
- The class-level
@Sqlloads the seed rows once, before any test transaction; then each test runs in its own rolled-back transaction. - The method-level
@Sql(statements = ...)runs inside that test's transaction, so its extra category exists only for that test. - The second test relies only on seed rows (category 7 has the pressure cooker). Note: MySQL does not roll back AUTO_INCREMENT, so a second insert in this class would get id 9; with several inserts, read ids from the response.
Example 4 · A test-data builder with defaults and unique SKUs
import java.math.BigDecimal;import java.util.concurrent.atomic.AtomicInteger;
record ProductRequest(String sku, String name, int categoryId, BigDecimal price, int stock, boolean isActive) { String toJson() { return "{\"sku\": \"" + sku + "\", \"name\": \"" + name + "\", \"categoryId\": " + categoryId + ", \"price\": " + price + ", \"stock\": " + stock + ", \"isActive\": " + isActive + "}"; }}
/** * A test-data builder: every field has a sensible default, a test changes only what it is about, * and each SKU is unique so two tests (or two runs) never clash on the unique constraint. */class ProductRequestBuilder { private static final AtomicInteger SEQUENCE = new AtomicInteger();
private String sku = "TST-" + String.format("%05d", SEQUENCE.incrementAndGet()); private String name = "Test Product"; private int categoryId = 4; // Accessories in the seed data private BigDecimal price = new BigDecimal("999.00"); private int stock = 10; private boolean active = true;
static ProductRequestBuilder aProduct() { return new ProductRequestBuilder(); }
ProductRequestBuilder named(String name) { this.name = name; return this; }
ProductRequestBuilder priced(String rupees) { this.price = new BigDecimal(rupees); return this; }
ProductRequestBuilder outOfStock() { this.stock = 0; return this; }
ProductRequestBuilder inactive() { this.active = false; return this; }
ProductRequest build() { return new ProductRequest(sku, name, categoryId, price, stock, active); }}
public class ProductBuilderDemo { public static void main(String[] args) { // Each line is what one test needs; everything else keeps its default System.out.println(ProductRequestBuilder.aProduct().build().toJson()); System.out.println(ProductRequestBuilder.aProduct().named("USB-C Cable 2m").priced("249.00").build().toJson()); System.out.println(ProductRequestBuilder.aProduct().outOfStock().build().toJson()); System.out.println(ProductRequestBuilder.aProduct().inactive().build().toJson()); }}{"sku": "TST-00001", "name": "Test Product", "categoryId": 4, "price": 999.00, "stock": 10, "isActive": true}
{"sku": "TST-00002", "name": "USB-C Cable 2m", "categoryId": 4, "price": 249.00, "stock": 10, "isActive": true}
{"sku": "TST-00003", "name": "Test Product", "categoryId": 4, "price": 999.00, "stock": 0, "isActive": true}
{"sku": "TST-00004", "name": "Test Product", "categoryId": 4, "price": 999.00, "stock": 10, "isActive": false}What this code does
aProduct()starts with valid defaults;named,priced,outOfStockandinactivechange one thing each.- The counter makes every SKU unique within a run, so two tests never clash on
uq_products_sku. For data that is committed across runs, reset first or add a run-specific part. - In a test,
aProduct().outOfStock().build().toJson()is the request body: the test reads as what it is about.
ShopLite's reset-test-db.sql empties every table with TRUNCATE (which also restarts the ids at 1) and loads the same seed rows as the dev data. Put it on the class, or use @Sql(statements = "INSERT ...") on one method. The four phases are BEFORE_TEST_CLASS, BEFORE_TEST_METHOD (the default), AFTER_TEST_METHOD and AFTER_TEST_CLASS.
A test-data builder is a small class that makes test objects or request bodies with sensible defaults, so each test changes one thing: aProduct().outOfStock().build().
Keeping tests independent: rollback, cleanup and unique values
An independent test passes alone, in any order and on every run. It never uses rows another test created and leaves nothing behind that could break the next test.
Four habits keep one test from breaking another:
- Rollback:
@Transactionalon a@DataJpaTestor a MockMvc@SpringBootTestundoes each test's changes. - Reset:
@Sqlwith the reset script before the class or each method, forRANDOM_PORTtests whose requests commit. - Unique values: SKUs, names and e-mails no other test or seed row uses, such as a counter in a builder.
- No hand-offs: never let one test use rows another test created; put the whole flow in one test.
Find the bug
Spot the dependency
Click the line that breaks independence.
This test passes in the full class but fails when run alone. Which line is the cause?
Round 1 of 2BEFORE_TEST_CLASS in a @Transactional class (as AccessMatrixIT does), so it runs outside the test transactions.Never pointing tests at a real database by accident
A guard is a test-only bean that checks the JDBC URL when the context starts and stops it unless the database is a local *_test one. A context that cannot start never runs @Sql, so nothing is emptied.
Make the test context refuse to start on the wrong database. Example 5 is the guard bean; Example 6 is its check in plain Java.
Example 5 · src/test/java/com/shoplite/TestDatabaseGuard.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
// src/test/java/com/shoplite/TestDatabaseGuard.javapackage com.shoplite;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;
/** * Lives in src/test, so it is never in the jar. Component scanning finds it in every * @SpringBootTest, and the context refuses to start unless the database is a local *_test one. * Slices that use the real database add @Import(TestDatabaseGuard.class). */@Componentpublic class TestDatabaseGuard {
public TestDatabaseGuard(@Value("${spring.datasource.url}") String url) { TestDatabaseUrls.requireTestDatabase(url); // the same check as the plain Java example below }}Running CategoryFlowIT without @ActiveProfiles("test"):
[ERROR] com.shoplite.category.CategoryFlowIT.createAndReadBack -- Time elapsed: 0.007 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@1f6c0a3d testClass = com.shoplite.category.CategoryFlowIT, ...]
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testDatabaseGuard' defined in file [...\target\test-classes\com\shoplite\TestDatabaseGuard.class]: Failed to instantiate [com.shoplite.TestDatabaseGuard]: Constructor threw exception
...
Caused by: java.lang.IllegalStateException: Refusing to run tests against database 'shoplite': the name must end with _test.
The context never started, so @Sql never ran: the dev data is safe.What this code does
- The guard is a normal
@Componentinsrc/test, so@SpringBootTestfinds it through component scanning and it never ships in the jar. - Its constructor runs while the context starts; throwing stops the context, and a failed context never runs
@Sql. - A Testcontainers database is called
test, not*_test; a project using containers would allow that name too.
Example 6 · The guard's check in plain Java
import java.net.URI;import java.util.List;
/** The check ShopLite's TestDatabaseGuard makes before any test may touch a database. */class TestDatabaseUrls { static void requireTestDatabase(String jdbcUrl) { if (jdbcUrl == null || !jdbcUrl.startsWith("jdbc:mysql://")) { throw new IllegalStateException("Refusing to run tests: not a MySQL URL: " + jdbcUrl); } URI uri = URI.create(jdbcUrl.substring("jdbc:".length())); String database = uri.getPath().substring(1); // "/shoplite_test" -> "shoplite_test" String host = uri.getHost(); if (!database.endsWith("_test")) { throw new IllegalStateException("Refusing to run tests against database '" + database + "': the name must end with _test."); } if (!host.equals("localhost") && !host.equals("127.0.0.1")) { throw new IllegalStateException("Refusing to run tests against host '" + host + "': use a local or container database."); } }}
public class DatabaseGuardDemo { public static void main(String[] args) { List<String> urls = List.of( "jdbc:mysql://localhost:3306/shoplite_test", "jdbc:mysql://localhost:3306/shoplite", "jdbc:mysql://db.shoplite.example:3306/shoplite_test", "jdbc:h2:mem:testdb"); for (String url : urls) { try { TestDatabaseUrls.requireTestDatabase(url); System.out.println("OK " + url); } catch (IllegalStateException e) { System.out.println("STOPPED " + e.getMessage()); } } }}OK jdbc:mysql://localhost:3306/shoplite_test STOPPED Refusing to run tests against database 'shoplite': the name must end with _test. STOPPED Refusing to run tests against host 'db.shoplite.example': use a local or container database. STOPPED Refusing to run tests: not a MySQL URL: jdbc:h2:mem:testdb
What this code does
- Only
jdbc:mysql://localhost/...URLs whose database name ends in_testpass. - The dev database
shoplite, any remote host and any other kind of database are stopped with a clear message. - Keeping the check in a plain class makes it easy to unit test, as this program does.
A test suite that runs TRUNCATE is dangerous on the wrong database, so ShopLite defends in layers: the test settings only read TEST_DB_URL, the database name ends in _test, the build itself turns the test profile on, and the guard checks the URL as the last layer.
Never put real passwords or a shared server's URL in application-test.properties. CI servers set TEST_DB_URL to their own throw-away database (the CI module shows how).
Predict the output
Does the guard stop it?
Pick what the guard does with each JDBC URL.
Round 1 of 3
What does the guard do?
Next step
Check your understanding
11 quick questions