Configure specific in memory database for testing purpose in Spring Configure specific in memory database for testing purpose in Spring spring spring

Configure specific in memory database for testing purpose in Spring


Spring profiles can be used for this. This would be a specific way:

Have environment specific properties files:

application.properties:

spring.profiles.active: dev

application-dev.properties

spring.jpa.database: MYSQLspring.jpa.hibernate.ddl-auto: updatespring.datasource.url: jdbc:mysql://localhost:3306/dbnamespring.datasource.username: usernamespring.datasource.password: password

application-test.properties

spring.jpa.database: HSQL

Have both MySQL and H2 drivers in pom.xml, like this:

<dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <scope>runtime</scope></dependency><dependency>    <groupId>org.hsqldb</groupId>    <artifactId>hsqldb</artifactId>    <scope>test</scope></dependency>

Last but not the least, annotate Test classes with @ActiveProfiles("test").


Another approach is to add the annotation @AutoConfigureTestDatabase to you test class.My tests usually look like this:

@RunWith(SpringRunner.class)@DataJpaTest@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)public class MyRepositoryTest {    @Autowired    MyRepository repository;    @Test    public void test() throws Exception {        // Tests...    }}

Note that the embedded database dependency needs to be added in the pom.xml file.For embedded database this annotation is not necessary it will work even if only the dependency is added in pom file.


@Sanjay has one way to put it but I find it confusing. You could just as well have only a production profile that you enable when you're in production, something like:

spring.jpa.hibernate.ddl-auto: updatespring.datasource.url: jdbc:mysql://localhost:3306/dbnamespring.datasource.username: usernamespring.datasource.password: password

And don't specify anything else. If you add an embedded database in test scope, it will be available in your tests. If you run your tests with the default profile (no customization whatsoever), it won't find any database information (since these are stored in the production profile). In that case, it will try to find an embedded database and start it for you. If you need more customization for some reason, you can have a application-test.properties for those (you'll need to add ActiveProfiles("test") to your test(s).