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.
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With