DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • A Guide to Container Runtimes
  • Gemma 3: Unlocking GenAI Potential Using Docker Model Runner
  • Docker vs Kubernetes: Which to Use and When?

Trending

  • Concourse CI/CD Pipeline: Webhook Triggers
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. 3 Ways to Use Docker Containers for Testing in Arquillian

3 Ways to Use Docker Containers for Testing in Arquillian

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.

By 
Alex Soto user avatar
Alex Soto
·
Mar. 27, 17 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
10.2K Views

Join the DZone community and get the full member experience.

Join For Free

Arquillian Cube is an Arquillian extension that can be used to manage Docker containers from Arquillian.

With this extension, you can start a Docker container(s), execute Arquillian tests, and shut down the container(s).

The first thing you need to do is add the Arquillian Cube dependency. This can be done by using 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.

1. Docker-Compose

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, starts all containers, executes the tests, and stops and removes 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 the previous example, a Docker compose file version 2 is defined (it can be stored in the root of the project, in src/{main, test}/docker, or in src/{main, test}/resources and Arquillian Cube will pick it up automatically), creates the defined network, starts the service defined container, and executes the given test. Finally, it stops and removes network and container. The key point here is that this happens automatically; you don't need to do anything manually.

2. Container Object

The second approach is using 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 look. Also, since you are using Java objects, you can add methods that encapsulate 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 the @Cube  annotation.

Notice that you can 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.

3. Container Object DSL 

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 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 here.

Docker (software)

Published at DZone with permission of Alex Soto, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • A Guide to Container Runtimes
  • Gemma 3: Unlocking GenAI Potential Using Docker Model Runner
  • Docker vs Kubernetes: Which to Use and When?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: