Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use embedded database for test in spring boot

I have a spring boot application, it has a couple of @Entity classes and @RepositoryRestResource repositort interfaces for them. Now I want to write some tests, where I can check that I can add a new record into my database using those repositories, but I don't want to use my configured MySQL database for it, but instead I want to use some embedded db like H2. At the moment I have an application.properties file, which 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 do I configure my app to use other db for tests? I have no xml in my project, everything is based on annotations. I tried to define @Configuration class with @Bean to create DataSource and then use it with @ContextConfiguration annotation on test class, but it says that it can't load context.

like image 242
Leonid Bor Avatar asked Feb 21 '17 14:02

Leonid Bor


People also ask

How do you test DataSource in spring boot?

Using a Standard Properties File in Spring Bootproperties. It resides in the src/main/resources folder. If we want to use different properties for tests, we can override the properties file in the main folder by placing another file with the same name in src/test/resources. The application.

What is embedded database in spring boot?

H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application.

Should integration tests use database?

Integration tests focus on testing how separate parts of the program work together. In the context of applications using a database, integration tests usually require a database to be available and contain data that is convenient to the scenarios intended to be tested.

Which database is used with spring boot?

Spring Boot gives you defaults on all things. For example, the default database is H2 . Consequently, when you want to use any other database, you must define the connection attributes in the application. properties file.


1 Answers

If you are using a Maven project, you can add a application.properties file into 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

Also, you need to include H2 as dependency (pom.xml):

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.193</version>
</dependency>
like image 193
Boni García Avatar answered Oct 15 '22 04:10

Boni García