Use the built-in database for testing in spring boot

I have a spring boot application, it has a couple of @Entity and @RepositoryRestResource repositort classes for them. Now I want to write some tests where I can verify that I can add a new record to my database using these repositories, but I do not want to use my customized MySQL database for it, but instead I want to use some built-in db like H2 . At the moment, I have an application.properties file that looks like this:

 spring.jpa.hibernate.ddl-auto=create spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=qwerty123 

Question: How to configure the application to use other db for tests? I do not have xml in my project, everything is based on annotations. I tried to define the @Configuration class with @Bean to create a DataSource , and then use it with the @ContextConfiguration annotation in the test class, but it says that it cannot load the context.

+5
source share
2 answers

If you are using a Maven project, you can add the application.properties file to your src/test/resources , for example, with the following content.

 # Create DDL spring.jpa.hibernate.ddl-auto=create # H2 in local file system allowing other simultaneous connections spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE 

In addition, you need to include H2 as a dependency ( pom.xml ):

 <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.193</version> </dependency> 
+13
source

You will need to use Spring Profiles - https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html#howto-set-active-spring-profiles

You define the active profile using "spring.profiles.active = development", and then include H2 in your development profile.

The examples use YAML, but they also work in standard property files.

+2
source

Source: https://habr.com/ru/post/1264519/


All Articles