Testcontainers recently passed over 1000 stars threshold. It is an perfect reason to pen a post about this utterly useful library.
Intro
When you write unit-tests for your code, you usually mock all the external dependencies, such as database calls or message queue polling. But what if you need to make integration tests with real dependencies? Usually, it is quite tricky, because in this case, you have to have real services installed in your system, which is not very convenient. Say, you want to write integration tests working with a database, in this situation you need a real database running on your local machine.
As you can see, it is kind of a problem and not flexible at all, because you run tests on other developers computers and CI servers and all these guys also need to run the database to make tests passing. Is there any convenient solution?
Solution
Introducing Testcontainers (★ 1006). This java-library allows you to set up your dependencies right from your integration tests using Docker containers. Your tests remain independent of other services because each test set up an individual environment for its runtime.
Look how easy to use it. Say, you need a Redis for your test, then you add the class rule like so:
and a spare Redis will be available for your tests on the 6379 port.
Please, refer to official documentation for more examples. This library also exists as a plugin for Spock framework and Scala tests.
#java #docker #tests #container #spock #scala
Intro
When you write unit-tests for your code, you usually mock all the external dependencies, such as database calls or message queue polling. But what if you need to make integration tests with real dependencies? Usually, it is quite tricky, because in this case, you have to have real services installed in your system, which is not very convenient. Say, you want to write integration tests working with a database, in this situation you need a real database running on your local machine.
As you can see, it is kind of a problem and not flexible at all, because you run tests on other developers computers and CI servers and all these guys also need to run the database to make tests passing. Is there any convenient solution?
Solution
Introducing Testcontainers (★ 1006). This java-library allows you to set up your dependencies right from your integration tests using Docker containers. Your tests remain independent of other services because each test set up an individual environment for its runtime.
Look how easy to use it. Say, you need a Redis for your test, then you add the class rule like so:
// Set up a redis container
@ClassRule
public static GenericContainer redis =
new GenericContainer("redis:3.0.2")
.withExposedPorts(6379);
and a spare Redis will be available for your tests on the 6379 port.
Please, refer to official documentation for more examples. This library also exists as a plugin for Spock framework and Scala tests.
#java #docker #tests #container #spock #scala