如何在自定义网络中将 JUnit 5 与测试容器一起使用?

How do I use JUnit 5 with testcontainers in a custom network?

我似乎无法让以下场景正常工作。我正在尝试创建一个场景 where two containers talked with each other on a separate network 使用 JUnit 5 结构。

@Testcontainers
class TestContainerTests {

  @BeforeAll
  static void setup() {

    networkName = RandomStringUtils.randomAlphabetic(20);
    network =
        Network.builder()
            .createNetworkCmdModifier(
                createNetworkCmd -> {
                  createNetworkCmd.withName(networkName);
                })
            .build();
  }

  private static String networkName;

  private static Network network;

  @Container
  private static GenericContainer<?> whoami =
      new GenericContainer<>("containous/whoami")
          .withNetwork(network)
              .withNetworkAliases("whoami")
          .withExposedPorts(80)
          .waitingFor(Wait.forLogMessage(".*Starting up on port 80.*", 1));

  /**
   * An alpine container that is set to sleep.  this is used for testing a specific scenario
   */
  @Container
  private GenericContainer<?> alpine =
          new GenericContainer<>("alpine")
                  .withCommand("sleep 600")
                  .withNetwork(network);

  @Test
  void testWhoAmI() {

    final var url =
        UriComponentsBuilder.newInstance()
            .scheme("http")
            .host("localhost")
            .port(whoami.getMappedPort(80))
            .toUriString();

    final var responseBody =
        WebTestClient.bindToServer()
            .baseUrl(url)
            .build()
            .get()
            .uri("/")
            .exchange()
            .expectStatus()
            .isOk()
            .expectBody(String.class)
            .returnResult()
            .getResponseBody();
    assertThat(responseBody).contains("GET / HTTP/1.1");
  }

  @Test
  void connection() throws Exception {

    // this fails connection
    final var wget = alpine.execInContainer("wget", "-qO-", "http://whoami/");
    System.err.println(wget.getStderr());
    assertThat(wget.getStdout()).contains("GET / HTTP/1.1");

  }


}

我知道我可以使用@BeforeAll 和@AfterAll 自己简单地管理生命周期,但我正在寻找一种方法让它与现有注释一起工作。

使用 Testcontainers 中的默认方法创建网络(在 @BeforeAll 生命周期方法之外)应该已经适合您: https://www.testcontainers.org/features/networking/#advanced-networking


@Testcontainers
class TestContainerTests {

  private static Network network = Network.newNetwork();

  // ...
}