Geeknarrator

post-header

 

Testing is one of the most critical parts of the Software Development Lifecycle. Writing meaningful unit/integration tests with enough coverage is really important. It saves your system from critical bug injection, helps meeting functional requirements and gives clear understanding of what the software component is doing.

Unit tests can also be performed by mocking external calls and test the functionalities that lie within the system boundaries. However if you want to test a component/unit/module along with the integration points you need the external services/components up and running during the test lifecycle.

Usually the idea is to create a test environment which can be used by the test cases. However it can be really expensive and time consuming to maintain a separate environment all together just for testing integration points. What can be done instead is, spinning up the dependencies just for the test lifecycle and then destroy the context once tests are completed. This approach is suitable because, tests do not depend on any environment which can be down (in bad shape) and is light weight. In order to achieve this test containers are really helpful.

TestContainers provide Java apis to manage lightweight containers for :

  • databases – data access layer tests
  • web servers – web layer tests
  • queuing systems – application integration points
  • search engines – ex. elastic search
  • logging services – ex. logstash

The coolest feature is the GenericContainers which can be used to spin up any kind of container during the test lifecycle.

Basically these are docker containers which are run to fulfil test dependency needs.

For example if you want PostgreSQL as a dependency you may simply do this :

PostgreSQLContainer<?> postreSQLContainer = new PostgreSQLContainer<>().
    withDatabaseName("db").withPassword("pass")
    .withUsername("user");
postgres.start();

This will start a PostgreSQL container for you and you can connect the the db using “pass” and “user” as credentials. (Default port – 5432)

If you want to create a connection you can simply do this and create a connection.

Connection connection = postreSQLContainer.createConnection("url params");

As you see its really convenient and lightweight. It hides all the complexity of pulling the docker image, starting the container and setting required properties.

To stop the container you can simply do :

postreSQLContainer.stop(); // Container will be stopped.

There are a lot of other features which can be explored here :

https://www.testcontainers.org/

Happy Testing !!

Previous post
Next post
Related Posts
Leave a Reply

Your email address will not be published. Required fields are marked *