Testing in Arquillian with Docker Containers

Arquillian is an open source testing platform for the JVM that enables to easily create automated integration, functional and acceptance tests for Java middleware. In this article, Alex Soto presents three options to use Arquillian Cube to manager Docker containers from Arquillian.

Author: Alex Soto, http://www.lordofthejars.com/

Arquillian Cube is an Arquillian extension that can be used to manager Docker containers from Arquillian. With this extension, you can start a Docker container(s), execute Arquillian tests and after that shutdown the container(s).

The first thing you need to do is add Arquillian Cube dependency. This can be done by using the Arquillian Universe approach:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.arquillian</groupId>
            <artifactId>arquillian-universe</artifactId>
            <version>${version.arquillian_universe}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.arquillian.universe</groupId>
        <artifactId>arquillian-junit-standalone</artifactId>
        <scope>test</scope>
        <type>pom</type>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${version.junit}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.arquillian.universe</groupId>
      <artifactId>arquillian-cube-docker</artifactId>
      <scope>test</scope>
      <type>pom</type>
    </dependency>
</dependencies>

Then you have three ways of defining the containers you want to start. The first approach is using the docker-compose format. You only need to define the docker-compose file required for your tests, and Arquillian Cube automatically reads it, start all containers, execute the tests and finally after that they stop and remove them.

version: '2'

services:
  pingpong:
    image: jonmorehouse/ping-pong
    ports:
      - "8080:8080"
    networks:
      app_net:
        ipv4_address: 172.16.238.10
        ipv6_address: 2001:3984:3989::10
      front:
      back:

networks:
  front:
    driver: bridge
  back:
    driver: bridge
  app_net:
    driver: bridge
    driver_opts:
      com.docker.network.enable_ipv6: "true"
    ipam:
      driver: default
      config:
      - subnet: 172.16.238.0/24
        gateway: 172.16.238.1
      - subnet: 2001:3984:3989::/64
        gateway: 2001:3984:3989::1
@RunWith(Arquillian.class)
public class PingPongTest {

  @HostIp
  String ip;

  @HostPort(containerName = "pingpong", value = 8080)
  int port;
  
  @Test
  public void should_execute_a_ping_pong() {
    URL pingPongServer = new URL("http://" + ip + ":" + port);
    // ...
  }
  
}

In previous example a Docker compose file version 2 is defined (it can be stored in the root of the project, or in src/{main, test}/docker or in src/{main, test}/resources and Arquillian Cube will pick it up automatically), creates the defined network and start the service defined container, executes the given test. and finally stops and removes network and container. The key point here is that this happens automatically, you don’t need to do anything manually.

The second approach is using the Container Object pattern. You can think of a Container Object as a mechanism to encapsulate areas (data and actions) related to a container that your test might interact with. In this case no docker-compose is required.

@RunWith(Arquillian.class)
public class FtpClientTest {

public static final String REMOTE_FILENAME = "a.txt";

@Cube
FtpContainer ftpContainer;

@Rule
public TemporaryFolder folder = new TemporaryFolder();

@Test
public void should_upload_file_to_ftp_server() throws Exception {

// Given
final File file = folder.newFile(REMOTE_FILENAME);
Files.write(file.toPath(), "Hello World".getBytes());

// When
FtpClient ftpClient = new FtpClient(ftpContainer.getIp(),
ftpContainer.getBindPort(),
ftpContainer.getUsername(), ftpContainer.getPassword());
try {
ftpClient.uploadFile(file, REMOTE_FILENAME, ".");
} finally {
ftpClient.disconnect();
}

// Then
final boolean filePresentInContainer = ftpContainer.isFilePresentInContainer(REMOTE_FILENAME);
assertThat(filePresentInContainer, is(true));

}

}
@Cube(value = "ftp",
        portBinding =  FtpContainer.BIND_PORT +  "->21/tcp")
@Image("andrewvos/docker-proftpd")
@Environment(key = "USERNAME", value = FtpContainer.USERNAME)
@Environment(key = "PASSWORD", value = FtpContainer.PASSWORD)
public class FtpContainer {

 static final String USERNAME = "alex";
 static final String PASSWORD = "aixa";
 static final int BIND_PORT = 2121;

 @ArquillianResource
 DockerClient dockerClient;

 @HostIp
 String ip;

 public String getIp() {
  return ip;
 }

 public String getUsername() {
  return USERNAME;
 }

 public String getPassword() {
  return PASSWORD;
 }

 public int getBindPort() {
  return BIND_PORT;
 }

 public boolean isFilePresentInContainer(String filename) {
  try(
   final InputStream file = dockerClient.copyArchiveFromContainerCmd("ftp",
           "/ftp/" + filename).exec()) {
   return file != null;
  } catch (Exception e) {
   return false;
  }
 
 }
}

In this case, you are using annotations to define how the container should looks like. As you are using Java objects, you can add methods that encapsulates operations with the container itself, like in this object where the operation of checking if a file has been uploaded has been added in the container object. Finally in your test you only need to annotate it with @Cube annotation.

Note that you could even create the definition of the container programmatically:

@Cube(value = "pingpong", portBinding = "5000->8080/tcp")
public class PingPongContainer {

  @HostIp
  String dockerHost;

  @HostPort(8080)
  private int port;

  @CubeDockerFile
  public static Archive<?> createContainer() {
    String dockerDescriptor = Descriptors.create(DockerDescriptor.class)
              .from("jonmorehouse/ping-pong")
              .expose(8080)
              .exportAsString();
    return ShrinkWrap.create(GenericArchive.class)
              .add(new StringAsset(dockerDescriptor), "Dockerfile");
  }

  public int getConnectionPort() {
    return port;
  }

  public String getDockerHost() {
      return this.dockerHost;
  }
}

In this case a Dockerfile file is created programmatically within the Container Object and used for building and starting the container.

The third way is using Container Object DSL. This approach avoids you from creating a Container Object class and use annotations to define it. It can be created using a DSL provided for this purpose:

@RunWith(Arquillian.class)
public class PingPongTest {

  @DockerContainer
  Container pingpong = Container.withContainerName("pingpong")
                                .fromImage("jonmorehouse/ping-pong")
                                .withPortBinding(8080)
                                .build();

  @Test
  public void should_return_ok_as_pong() throws IOException {
    String response = ping(pingpong.getIpAddress(), pingpong.getBindPort(8080));
    assertThat(response).containsSequence("OK");
  }
}

In this case, the approach is very similar to the previous one, but you are using a domain-specific language (DSL) to define the container. You’ve got three ways, the first one is the standard one following docker-compose conventions, the other ones can be used for defining reusable pieces for your tests.

You can read more about Arquillian Cube at http://arquillian.org/arquillian-cube/

About the Author

Alex Soto is a software engineer at Red Hat. He is a passionate of Java world, software automation and he believes in the open source software model. He is a member of JSR374 (Java API for JSON Processing) Expert Group. Currently Alex is co-writing Testing Java Microservices book for Manning and he is an international speaker presenting his talks at software conferences like Devoxx, JavaOne, JavaZone or JavaLand. This article was originally published on http://www.lordofthejars.com/2017/03/3-ways-of-using-docker-containers-for.html and is reproduced with permission from Alex Soto.