Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to one-off run @DataJpaTest against real database instead of in-memory with Spring Boot

I am using Spring Boot 1.4.3 and have a whole bunch of tests that are annotated with @DataJpaTest. By default, they run against an in-memory database. I would like to be able to run all of them against a local MySQL temporarily. How can I do this in an easy way?

I have found that I can make it work for one by adding @ActiveProfiles("local") where I have an application-local.properties that points to my local MySQL, but it is just too much work to add that everywhere, run the tests and then remove it again (since I only want to run this manually against MySQL, the CI environment will run against the in memory db).

I am using Maven if that would matter.

UPDATE:

So I have an application-local.properties which contains the db properties to connect to my local MySQL database (Which I use already to run my application against the local MySQL)

Then I right-click in IntelliJ on a package and select "Run all tests in package". In the settings of that run configuration, I add -Dspring.profiles.active=local to the "VM options" field.

I would have thought that this would activate the local profile during the tests, but it does not. If I stop the local MySQL, the tests still run fine.

like image 350
Wim Deblauwe Avatar asked Jan 12 '17 13:01

Wim Deblauwe


People also ask

What is the use of @DataJpaTest?

@DataJpaTest is used to test JPA repositories. It is used in combination with @RunWith(SpringRunner. class) . The annotation disables full auto-configuration and applies only configuration relevant to JPA tests.

How do you handle database in spring boot?

To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.


1 Answers

You can add the profile with the MySQL datasource properties in the same application.properties (or .yml) as:

application.yml

# Existing properties

---
spring:
  profiles: h2
# More h2-related properties

---
spring:
  profiles: postgres
  database:
    driverClassName: org.postgresql.Driver
  datasource:
    url: jdbc:postgresql://localhost:5432/db_dvdrental
    username: user_dvdrental
    password: changeit
  jpa:
    database: POSTGRESQL
    generate-ddl: false
# More postgres-related properties

and either use @ActiveProfiles("postgres") in an integration test class or start teh container using VM argument as:

java -Dspring.profiles.active=h2 ...
like image 181
ootero Avatar answered Oct 12 '22 23:10

ootero