San Jaisy
San Jaisy

Reputation: 17048

Running TestContainer once for each Unit/Integration test in JUnit5 with Micronaut application

I am using a Test container with JUnit 5 in Micronaut application. I have many integration tests and I want to create and run the Test container once for each integration test.

**1st test on different file **

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@MicronautTest
public class DiscountGetListenerTest extends TestContainerFixture {
    @Inject
    static IDiscountProducer iDiscountProducer;
    
    @Test
    @DisplayName("Should return the discount based on the specified id")
    void shouldReturnTheDiscountBasedOnTheSpecifiedId() {
    }
}

2nd test on different file

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@MicronautTest
public class DiscountListenerTest extends TestContainerFixture {
    @Inject
    IDiscountProducer iDiscountProducer;

    @Test
    @DisplayName("Should return discounts list")
    void shouldReturnDiscountsList() {
        var item = iDiscountProducer.Find(new DiscountCriteriaCommand(null)).blockingGet();
        assertTrue(item.size() == 0);
    }
}

Test container fixture

@Testcontainers
public class TestContainerFixture {
    @Container
    public GenericContainer mongoDBContainer = new GenericContainer(DockerImageName.parse("mongo:4.0.10"))
            .withExposedPorts(27017);
    @Container
    public GenericContainer rabbitMQContainer = new GenericContainer(DockerImageName.parse("rabbitmq:3-management-alpine"))
            .withExposedPorts(5672);
}

When I run the application on each Integration test the container is created and started, however, I want to create once and start the container once

For example

enter image description here

On each test case the container is created and staring... How can I create and start the container once ??

Upvotes: 1

Views: 968

Answers (1)

kmcakmak
kmcakmak

Reputation: 149

Maybe you can try singleton container pattern explained in here: https://www.testcontainers.org/test_framework_integration/manual_lifecycle_control/

So for your code :

public abstract class TestContainerFixture {
    public static final GenericContainer mongoDBContainer;
    public static final GenericContainer rabbitMQContainer;
    
    static {
       mongoDBContainer = new GenericContainer(DockerImageName.parse("mongo:4.0.10"))
            .withExposedPorts(27017);
       rabbitMQContainer = new GenericContainer(DockerImageName.parse("rabbitmq:3-management-alpine"))
            .withExposedPorts(5672); 
       mongoDbContainer.start();
       rabbitMQContainer.start();
}

}

And when you extend this abstract class in your test, maybe that would work.

Upvotes: 1

Related Questions