Spring+kotlin+mongo+testcontainer
Introduction
In this project we shall see how to use testcontainer to test the repository created in mongodb As per their document Testcontainers is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.
Prerequisit
- Docker
Create sample project
Go to the spring initializer and create project with language as kotlin and dependencies required are webflux
& reactive mongo db
Here we shall create a loan details application, where we will save loan details.
Dependency for testcontainer
We need following depencies to add testconainer in the appliation
Container Configuration
Create docker compose file for the test container we shall use the same docker-compose.yml file as we are using for the application, except we shall change the port for the test docker container. it should look like this-
Note: here we are mapping docker container port at 1234
some random port it can be any number that are available.
The file path should be src/test/resources/docker-compose-test.yml
Create a container class that extends docker compose container class be used as mongo container
The code is very simple and self explanatory, at line:2
we create a DockerComposeContainer
of type SELF
MongoContainer
and provide path of test docker compose file.
We created it as a singleton repository and use @PostConstruct
to start the container once the dependency injection is done.
That’s all we need to start with testconatainer.
Create basic structure of the application
Create a document
class to save in mongo
Create an repository
to access data from the DB.
Create an service
class to access the loan details.
Create first test case
Let’s create our first test case as below
The test case is preety normal and same we write. There is nothing special we need to do for testcontainers here.
Run Test
Before run local test do ensure that the docker is running on your machine.
Repository
Create repository and link here.