Spring Boot 4 Testing / Part 6YOUTUBE PLAYER LOADS ON PLAYTesting Repository Layer
Spring Boot Testing #6

Spring Boot @DataJpaTest Tutorial: Test JPA Queries on a Real Database

Spring Boot 4 Testing3 Nov 20264:19Open on YouTube

In this lesson

Our cinema app keeps its bookings in a record book: the BookingRepository. One method Spring writes for us, one is a query we wrote ourselves. A stand-in (mock) can't tell us if that query is right, so today we test it against a real, small database.

Episode 5 of Spring Boot Testing: the complete guide. Same cinema booking app, one layer per episode.

  • Why a mock can't check a query, and why you need a real database
  • @DataJpaTest: a slice that starts only the repositories, with H2 in memory
  • Rollback: every test is erased at the end, so each test starts clean
  • Version note: what changed in Spring Boot 4 (@DataJpaTest's new package, the new test starter) and @MockBean vs @MockitoBean
  • Tests: findByShowId returns only one show's bookings; seatsSold adds up the seats
  • Guess first: we remove coalesce from the query. What happens for a show with no bookings?
  • What happens when rollback is turned off

Next: Ep 6, the whole app together: @SpringBootTest with a real Postgres in a container (Testcontainers).

Built and run on Spring Boot 4.1, Java 21, JUnit 6, H2 2.4.

Keep going

More walkthroughs.