DataJpaTest “Failed to replace DataSource with an embedded database for tests” issue

I have been playing around with JPA and testing of persistence layer in Spring Boot after a while of not touching it. After configuring needed dependency and adding needed annotations to my repository test class I got weird error, saying “Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.”

 

But let’s start from scratch. My pom.xml has been updated with Spring Boot test library:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

 

Below you can find the example of Spring Data CrudRepository implementation

public interface RoutePointsRepository extends CrudRepository<RoutePoint, UUID> {
}

 

And the test class using Junit5:

@ExtendWith(SpringExtension.class)
@DataJpaTest
public class TestDayRouteRepository {

    @Autowired
    private EntityManager entityManager;

    @Autowired
    private DayRouteRepository dayRouteRepository;

    @AfterEach
    private void tearDown(){
        entityManager.clear();
    }

    @Test
    @DisplayName("Test if all DayRoutes are returned")
    public void testGetAllDayRoutes(){
        entityManager.persist(trip);

        var dayRoutes = dayRouteRepository.findAll();

        assertEquals(2, ((Collection<?>)dayRoutes).size());
    }

}

 

After running above test this error has been shown: “Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.”.¬†Using mentioned annotation didn’t solve the issue, however gave a nice tip:

@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)

Newly produced error shown me what I did wrong:¬†“Caused by: java.lang.IllegalStateException: Driver for test database type [H2] is not available”. Of course! I forgot to include H2 dependency! So the only thing I needed to fix is to add following entry in pom.xml:

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>test</scope>
</dependency>

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
Website