Why in-memory databases can hide bugs
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's repository tests are green on H2, yet the same code could fail on the MySQL 8.4 database production uses. How can a passing test be wrong, and what should ShopLite's tests run on instead?
Recap: repository and integration tests from Section 18
An in-memory database is a database that lives inside the test's JVM and disappears when the test ends, such as H2. It is fast and needs no setup, but it is not the database that production runs.
With H2 on the test classpath, @DataJpaTest swaps ShopLite's DataSource for H2. The test below looks harmless, but it now asks whether the code works on H2.
@DataJpaTest // with H2 on the test classpath: an in-memory H2class ProductRepositoryTest {
@Autowired ProductRepository products;
@Test void findsProductBySku() { assertThat(products.findBySku("MOB-RN13")).isPresent(); }}Section 18 taught two Spring tests that touch a database: @DataJpaTest (only JPA, Flyway and the repositories, rolled back after each test) and @SpringBootTest (the whole app, called over HTTP). Both need a database, and a green test on H2 answers "does it work on H2?", not "does it work on MySQL 8.4?".
Dialect: syntax and functions that differ
A SQL dialect is the set of syntax rules and functions that one database understands. MySQL and H2 both speak SQL, but each adds its own rules, so a statement can work on one and fail on the other.
ShopLite's native queries use MySQL syntax. A statement can pass on H2 and fail on MySQL, as this query for the products of the five latest orders does.
Example 1 · A query H2 accepts and MySQL rejects
Runs in: a MySQL 8.4 client connected to the shoplite database
-- "Products from the 5 most recent orders"SELECT nameFROM productsWHERE product_id IN ( SELECT oi.product_id FROM order_items oi JOIN orders o ON o.order_id = oi.order_id ORDER BY o.ordered_at DESC LIMIT 5);ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
What this code does
- Inside a native
@Query, this passes a repository test on H2 and throws on MySQL 8.4, the first time a real user opens the page. - The MySQL fix is to wrap the limited query in a derived table (
SELECT product_id FROM (SELECT ... LIMIT 5) AS recent) or use a JOIN. Only a test on MySQL proves the fix.
Four kinds of difference break real projects: functions (DATE_FORMAT, JSON_EXTRACT), JSON and ENUM columns (validation and sorting rules), LIMIT inside IN (subquery) (MySQL rejects it) and locking such as FOR UPDATE SKIP LOCKED under load.
Flyway scripts split the same way. Scripts written for MySQL can fail on plain H2, so teams keep a second "H2-friendly" set that drifts from production. H2's MODE=MySQL is worse: it is still H2, so it can accept a statement that real MySQL rejects, and the first error appears during a deploy.
Predict the output
Will MySQL 8.4 run it?
Read each query and pick what MySQL 8.4 does.
Round 1 of 3
The query from the example, run on MySQL 8.4.
MODE=MySQL makes H2 behave like MySQL. It only accepts more MySQL syntax; the engine underneath is still H2.Collation and DECIMAL: same data, different answers
A collation is the set of rules a database uses to compare and sort text. MySQL's utf8mb4_0900_ai_ci ignores accents (ai) and letter case (ci), while H2 compares text exactly by default.
Two quiet differences give wrong answers instead of errors: ShopLite's emails compare by collation, and averages of money come back with a different scale.
Example 2 · Collation: same email or not?
import java.text.Collator;import java.util.HashSet;import java.util.List;import java.util.Locale;import java.util.Set;import java.util.TreeSet;
public class CollationDemo { public static void main(String[] args) { String saved = "Asha.Rao@example.com"; String typed = "asha.rao@example.com";
// Like H2's default: exact, case-sensitive comparison Set<String> caseSensitive = new HashSet<>(List.of(saved));
// Like MySQL utf8mb4_0900_ai_ci: ignores case and accents Collator aiCi = Collator.getInstance(Locale.ROOT); aiCi.setStrength(Collator.PRIMARY); Set<String> mysqlLike = new TreeSet<>(aiCi); mysqlLike.add(saved);
System.out.println("case-sensitive finds the email : " + caseSensitive.contains(typed)); System.out.println("_ai_ci finds the email : " + mysqlLike.contains(typed)); String accented = "café"; // café with an accented e System.out.println("Cafe = accented cafe in _ai_ci : " + (aiCi.compare("Cafe", accented) == 0)); }}case-sensitive finds the email : false _ai_ci finds the email : true Cafe = accented cafe in _ai_ci : true
What this code does
- A
CollatorwithPRIMARYstrength ignores case and accents, a close model of MySQL's_ai_cicollations; aHashSetcompares exactly, like H2's default. The model is simplified, but the effect is real. - So
existsByEmail("asha.rao@example.com")istrueon MySQL andfalseon H2. A sign-up test on H2 checks the wrong behaviour, and the unique email constraint also acts differently.
Example 3 · DECIMAL results: equals versus compareTo
import java.math.BigDecimal;
public class DecimalScaleDemo { public static void main(String[] args) { BigDecimal expected = new BigDecimal("1499.50"); // MySQL: AVG over DECIMAL(10,2) returns 2 + 4 = 6 decimal places BigDecimal fromMySqlAvg = new BigDecimal("1499.500000");
System.out.println("scales : " + expected.scale() + " vs " + fromMySqlAvg.scale()); System.out.println("equals : " + expected.equals(fromMySqlAvg)); System.out.println("compareTo : " + (expected.compareTo(fromMySqlAvg) == 0)); }}scales : 2 vs 6 equals : false compareTo : true
What this code does
BigDecimal.equalscompares the value and the scale, so1499.50and1499.500000are not equal. An assertion written against H2's result can fail on MySQL, or the other way round.- Compare money with
compareTo(in AssertJ:isEqualByComparingTo), and run the test on the engine whose numbers you ship.
MySQL's AVG of a DECIMAL(10,2) returns 6 decimal places, so an assertion written against H2's 1499.50 can fail on 1499.500000.
Collation also decides whether the unique constraint on customers.email rejects Asha.Rao@example.com after asha.rao@example.com: MySQL says yes, H2 says no.
Fix the error
Fix the test for MySQL
Read the real failure, then pick the line that fixes the test.
Round 1 of 2
An order report test fails on MySQL: the average has 6 decimals.
Error
org.opentest4j.AssertionFailedError: expected: 2499.50 but was: 2499.500000
The rule: same engine, same version as production
Testcontainers is a Java library that starts a real service, such as MySQL, in a Docker container for your tests and removes it afterwards. The tests then run on the same engine as production.
Test against the same engine and version you run in production: for ShopLite that is MySQL 8.4, not "some MySQL" and not H2. Pin the tag exactly as in compose.yaml.
Example 4 · Same engine, same version: a check you can automate
import java.util.Map;
public class SameVersionDemo { static String major(String image) { return image.substring(image.indexOf(':') + 1); }
public static void main(String[] args) { String production = "mysql:8.4"; Map<String, String> testSetups = Map.of( "H2 in MySQL mode", "h2:2.3", "MySQL latest", "mysql:latest", "MySQL 8.4", "mysql:8.4");
for (String name : new String[] {"H2 in MySQL mode", "MySQL latest", "MySQL 8.4"}) { String image = testSetups.get(name); boolean sameEngine = image.startsWith("mysql:"); boolean sameVersion = sameEngine && major(image).equals(major(production)); System.out.printf("%-17s engine %-5s version %s%n", name, sameEngine ? "same" : "diff", sameVersion ? "same" : "diff"); } }}H2 in MySQL mode engine diff version diff MySQL latest engine same version diff MySQL 8.4 engine same version same
What this code does
- Only the last setup tests what production runs.
mysql:latestis the same engine but can jump to a new major version on any day, with new reserved words and defaults. - Keep the tag in one place (a constant or a property) and use the same value in
compose.yaml, tests and production.
Pure unit tests with no database stay as they are: fast and free of Docker. The rest of this module sets Testcontainers up for ShopLite.
Find the bug
Find the line that breaks the rule
Production runs MySQL 8.4. Tap the line that breaks the same-engine, same-version rule.
A container for the repository tests.
Round 1 of 2The cost, and how it pays off
A real MySQL in tests is not free, and the numbers decide how to set it up. Here is the cost of three options for a suite of 12 test classes.
Example 5 · What a real database costs per test run
public class TestCostDemo { public static void main(String[] args) { int testClasses = 12; double h2StartSeconds = 0.5; // per Spring context with H2 double mysqlContainerSeconds = 12; // one MySQL container start
double h2 = testClasses * h2StartSeconds; double containerPerClass = testClasses * mysqlContainerSeconds; double sharedContainer = mysqlContainerSeconds;
System.out.printf("H2 for every class : %5.1f s%n", h2); System.out.printf("New MySQL container per class: %5.1f s%n", containerPerClass); System.out.printf("One shared MySQL container : %5.1f s%n", sharedContainer); }}H2 for every class : 6.0 s New MySQL container per class: 144.0 s One shared MySQL container : 12.0 s
What this code does
- The numbers are rough assumptions for a laptop, not measurements, and the one-time image download is left out. A container per test class is what makes people give up on real databases.
- One shared container costs about the same order as H2 and tests the real engine; the shared-container lesson shows how.
The costs are:
- Every developer machine and the CI server need Docker.
- The first run downloads the MySQL image (a few hundred MB, once).
- Each container start takes several seconds instead of milliseconds.
The usual answer is to start one container and share it across all test classes, which the shared-container lesson shows. Then the extra cost is a few seconds per run, against bugs customers would otherwise find.
Next step
Check your understanding
11 quick questions