Search code examples
postgresqlspring-bootunit-testingjpah2

is there any way to write test cases for repositories in spring boot without using H2 daatabase?


I am working on a Spring Boot application and need to write test cases for my repository layer in a way like database should create using my flyway script. However, I want to avoid using an in-memory database like H2 or connecting to an actual database for these tests(if possible).

Is there a way to the database interactions in Spring Boot so that I can test my repository methods? If so, could you please provide some guidance or examples on how to achieve this?

Here is a brief overview of my setup:

Spring Boot version: 3.0.5 Repository interface: Extends JpaRepository postgresql: 42.6.0 flyway: 9.16.3 Thank you in advance for your help!

I have tried in H2 using flayway script but it is not working, and giving syntax error beacuse my script contains script for postgresql. and i want to do it using only flayway script.


Solution

  • The first thing to ask is always: What do you really want to test. And the repositories isn't really a proper answer to that. What you really want to test is probably, something like:

    If I call MyRepository.x with parameters y, z I want to get this result back, and not the rows with green mubblewumps.

    If the repository behaves like this depends on

    • the correct implementation of Spring Data JPA, which depends on the correctness of your JPA implementation.
    • and it depends on the actual database.

    Therefore there is no way around it: you need a real database, and one that is as close to your production database as possible. And you already noticed that H2 doesn't cut it because it doesn't understand your scripts that (I assume) work fine on an actual Postgres database.

    Therefore: Use a real Postgres Database managed by Testcontainers