robert trudel
robert trudel

Reputation: 5749

How to change database testing

I use spring boot 2.0 and use Postgres for database part.

Is there a way to use postgres database instead of memory database or something h2 or hsqldb for testing?

Upvotes: 0

Views: 2808

Answers (2)

robert trudel
robert trudel

Reputation: 5749

Possibility in a junit test to write

@DataJpaTest @AutoConfigureTestDatabase(replace=Replace.NONE)

that will use default database of the profile

Upvotes: 1

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

Put PostgreSQL dependency to your classpath (Maven pom.xml example):

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

Update application.yml config file:

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/dbname?user=dbuser&password=dbpasswd
    driverClassName: org.postgresql.Driver

In this example JDBC URL uses dbname database name, dbuser username and dbpasswd password.

Use PosrgreSQL while running tests

You haven't specify it directly in question, but you may be interested in running integration tests with PostgreSQL database. If so there is one thing you have to do. Create a new config file called application-it.yml (it stands for "integration test") and put the content I mentioned above there. You can also change your dependency definition to:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>test</scope>
</dependency>

so PostgreSQL driver will be available only in test scope. Next when you write an integration test, annotate it with:

@ActiveProfiles("it")

so spring will pick application-it.yml configuration file to set up database connection.

Reference: http://docs.spring.io/spring-boot/docs/2.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-connect-to-production-database

Bonus: using embedded PostgreSQL

You may be interested in running integration tests with embedded PostgreSQL. You can use this library:

https://github.com/yandex-qatools/postgresql-embedded

And here you can find an example of how to use it with Spring Boot for testing:

https://gist.github.com/Opalo/792c38c689fbedd762670812cb9f7e7c

Using embedded PostgreSQL has one significant advantage - you don't have to setup the database manually. You can use it in your local development as well as with continuous integration server. Hope it helps.

Upvotes: 1

Related Questions