运行 使用 Micronaut 应用程序在 JUnit5 中对每个 Unit/Integration 测试进行一次 TestContainer

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

我在 Micronaut 应用程序中使用带有 JUnit 5 的测试容器。我有很多集成测试,我想为每个集成测试创建并 运行 一次测试容器。

**对不同文件的第一次测试**

@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() {
    }
}

对不同文件的第二次测试

@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);
    }
}

测试容器夹具

@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);
}

当我 运行 应用程序在每个集成测试中创建并启动容器时,但是,我想创建一次并启动一次容器

例如

在每个测试用例中创建并启动容器...我怎样才能创建并启动一次容器??

也许你可以尝试这里解释的单例容器模式:https://www.testcontainers.org/test_framework_integration/manual_lifecycle_control/

所以对于您的代码:

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();
}

}

当您在测试中扩展此摘要 class 时,也许会奏效。