TP6
TP6
If you’re not familiar with test containers visit the web site https://java.testcontainers.org/
Testcontainers is a library that supports JUnit tests providing lightweight instances of common
software like databases, web browsers, RabitMQ that can run in a Docker container.
In our application, we need a module for postgres, it is indicated in the web site how to use it
https://java.testcontainers.org/modules/databases/postgres/
but before we have to integrate the test container to our application, if we want multiple
dependencies one for postgres, one for Kafka for example, we add the maven dependencies code to
pom.xml file
And load the maven changes , then install the postgres container (for that we go to modules>
databases and choose postgres
We then want to add the module for Junit5, we go to test framework integration and choose JUnit5
For docker we go to spring initializr and choose Docker Compose Support dependency then explore
and copy the dependency code in our pom.xml
Configure Compose.yaml
Go to product service java test class
@BeforeEach
void setUp(){
productRepository.saveAll(products);
@Test
void shouldReturProductByName(){
assertThat(product).isNotNull();
if it appears an error message with the second test then the table does not exist
in application.properties we put
For the controller, we create an integration test for our controller now. We select our controller and
click on create test
Once creater we add this annotation to attibute a random port test on Tomcat and a test container
annotation to your class
Then add container
TestRestTemplate and RestTemplate are clients that are quite suitable for writing integration tests
and can handle communicating with HTTP APIs very well.