Spring: test your MySQL JPA with H2


If in Spring Boot you are using a database you can use for your tests H2 or another similar embedded database.

In our case we are using MySQL / PostgreSQL for production and we want to test our code using @DataJpaTest.

Some relevant information from the documentation:

Annotation for a JPA test that focuses only on JPA components.
Using this annotation will disable full auto-configuration and instead apply only configuration relevant to JPA tests.
By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test. They also use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource).

Include the DB in the classpath

In our case we use H2, we import the library in Maven


You have to tell Spring to use the H2 database during the tests, for this you have to create /src/test/resources/application.properties with the connection information for H2


We create the test class with the required dependencies

import org.junit.jupiter.api.Test; 
import org.junit.runner.RunWith; 
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 
import org.springframework.test.context.junit4.SpringRunner; 
import org.springframework.transaction.annotation.Propagation; 
import org.springframework.transaction.annotation.Transactional; 
import static org.assertj.core.api.Assertions.*; 
@Transactional(propagation = Propagation.NOT_SUPPORTED) 
class FoodControllerTest { 
    FoodRepository carbsRepository; 
    void createFood() { 

Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).