Spring Boot JUnit5 testing without database connection

Viewed 96

I am running into a problem where I am running test with Spring Boot that comes with JUnit5. I have my application's connection to a Datasource in the cloud. However, when I run my test, it is failing for for one reason which is, I have my datasource file set to take in environment variables and did not hard code my data sources in (will be sent through docker-compose file). Is there a way to create a fake db in memory when testing? How do I go about this as I will I am also trying to test by mocking out my database.

Main Test.java file

package com.legacybanking.legacyBankingAPI;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
class LegacyBankingApiApplicationTests {

    @Test
    void contextLoads() {
    }

}

datasource

spring.datasource.url=${SPRING_DATASOURCE_URL}
spring.datasource.username=${SPRING_DATASOURCE_USERNAME}
spring.datasource.password=${SPRING_DATASOURCE_PASSWORD}
spring.jpa.hibernate.ddl-auto=${SPRING_JPA_HIBERNATE_DDL_AUTO}
spring.jpa.show-sql=${SPRING_JPA_SHOW_SQL}
spring.jpa.properties.hibernate.dialect=${SPRING_JPA_PROPERTIES_HIBERNATE_DIALECT}
spring.jpa.properties.hibernate.format_sql=${SPRING_JPA_PROPERTIES_HIBERNATE_FORMAT_SQL}
1 Answers

Definitely there is! If you want "the real thing" - that is a real DB against which you run your queries, I'd go with testcontainers. They require a Docker demon installed and running on your machine, but other than that they are a great way to provide test dependencies (databases, messaging queues, Kafka, you name it), and are quite easy to setup and teardown in your test cases.

Alternatively, you can provide a dedicated configuration file for your integration (in Spring's meaning of the term "integration") tests, and using Spring profiles feature simply instantiate In-Memory versions of your repositories which do not require DB at all - you can write your own fakes that keep all the data in memory.

Both approaches have their pros and cons. Running real db in a docker environment is a kind of a heavy-weight approach, the tests are slow comparing to using in-memory fakes. The pro side is that your are making real queries against a real db, and if your query is faulty you'll get to know that. Also developing and maintaining test fakes takes some time and effort, so there is a tradeoff here.

TL;DR - checkout testcontainers and Martin Fowler's article - choose what suites your needs the most.

Related