javatestcontainerstestcontainers-junit5

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


I can't seem to get the following the following scenario to work. I am trying to create a scenario where two containers talked with each other on a separate network using JUnit 5 constructs.

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

  }


}

I am aware I can simply manage the lifecycle myself using @BeforeAll and @AfterAll, but I am looking for a way to get it working with the existing annotations.


Solution

  • Using the default methods from Testcontainers for creating networks (outside of @BeforeAll lifecycle methods) should already work for you: https://www.testcontainers.org/features/networking/#advanced-networking

    
    @Testcontainers
    class TestContainerTests {
    
      private static Network network = Network.newNetwork();
    
      // ...
    }