Mocks on spring project
Project sampling test scenarios using spring capabilities.
Requirements
- java 21
- docker 28
Project setup
Using spring initializer, scaffold a project.
Add this extra dependency:
xml
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>Using docker, spin a postgresql database:
bash
docker run --rm -d \
--name pg-database -p 5432:5432 \
-e POSTGRES_PASSWORD=enterprise \
-e POSTGRES_USER=enterprise \
-e POSTGRES_DB=products \
postgres:16-alpineModify TestcontainersConfiguration to provide a test database:
kotlin
// ...
@TestConfiguration(proxyBeanMethods = false)
class TestcontainersConfiguration {
@Bean
@ServiceConnection
fun postgresContainer(): PostgreSQLContainer<*> = PostgreSQLContainer(
DockerImageName.parse("postgres:16-alpine")
).withEnv(
mapOf(
"POSTGRES_DB" to "products",
"POSTGRES_USER" to "enterprise",
"POSTGRES_PASSWORD" to "enterprise"
)
)
}Finally add the default liquibase configuration and the fist migration:
bash
mkdir -p src/main/resources/db/changelog/migrations
touch src/main/resources/db/changelog/migrations/2025-05-01-initial-schema.sql
touch src/main/resources/db/changelog/db.changelog-master.yamlAnd that's it, the project is
How to build
bash
./mvnw packageHow to run
bash
./mvnw springboot:runHow to test
bash
./mvnw testNoteworthy
- avoid the
org.junit.Testannotation, use the new one atorg.junit.jupiter.api.Test