Skip to content

Example: TestContainers

David Matějček edited this page Aug 8, 2024 · 1 revision

Simple Test

This is probably the simplest possible test with GlassFish and TestContainers. It automatically starts the GlassFish Docker Container and then stops it after the test. The test here is quite trivial - downloads the welcome page and verifies if it contains expected phrases.

If you want to run more complicated tests, the good path is to

  1. Write a singleton class managing the GlassFish Docker Container or the whole test environment.
  2. Write your own Junit5 extension which would start the container before your test and ensure that everything stops after the test including failures.
  3. You can also implement direct access to the virtual network, containers, so you can change the environment configuration in between tests and simulate network failures, etc.
@Testcontainers
public class WelcomePageITest {

    @Container
    private final GenericContainer server = new GenericContainer<>("ghcr.io/eclipse-ee4j/glassfish:latest").withExposedPorts(8080);

    @Test
    void getRoot() throws Exception {
          URL url = new URL("http://localhost:" + server.getMappedPort(8080) + "/");
          StringBuilder content = new StringBuilder();
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();
          try {
              connection.setRequestMethod("GET");
              try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                  String inputLine;
                  while ((inputLine = in.readLine()) != null) {
                      content.append(inputLine);
                  }
              }
          } finally {
              connection.disconnect();
          }
          assertThat(content.toString(), stringContainsInOrder("Eclipse GlassFish", "index.html", "production-quality"));
      }

}