Hello, dear Java warrior! ? If you are here, then it’s time to get on the testing path and prove that your code works better than what marketers promise. Today we will talk about testing logic in Spring using an H2 database. Let's go! ?
Imagine: you are writing the coolest service, but you are afraid that your business logic lives in a world of illusions. You don't want tests to drive the real database because:
Before we start, let's prepare our cozy test little world. To do this, we will write the necessary settings in src/test/resources/application.properties. Voila:
# Подключаем H2 spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password # Убедимся, что Hibernate всё за нас делает spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.url: indicates that we want to use an "in-memory" database (mem:testdb), which will disappear as soon as we turn off the tests.
DB_CLOSE_DELAY=-1: the database will live until the end of the JVM (long live stability!).
spring.jpa.hibernate.ddl-auto=create-drop: we create a database when running tests, delete it after. Cleanliness is the key to success.
For Maven
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency>
For Gradle
implementation 'com.h2database:h2'
Now let's write our tests. We turn on Spring, the magic of annotations and a little love for code.
Let's say we have a User entity:
# Подключаем H2 spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password # Убедимся, что Hibernate всё за нас делает spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Testing adding a user
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency>
@SpringBootTest: Raising the Spring context (everything is like in production, but safe).
@Autowired: Dependency injection because we deserve it.
UserRepository: your repository works like in battle.
Now you know how to create friendship between Spring, H2 and tests. These examples are your key to a world where there are no bugs and tests work the first time. Don't forget: tests don't make your code better, but they do help you sleep soundly. Good luck! ?
The above is the detailed content of H fun tests in Spring. For more information, please follow other related articles on the PHP Chinese website!