An Efficient Object Storage for JUnit Tests
There are several limitations to store and fetch such data —to resolve the problem it was suggested to find more suitable data storage.
Join the DZone community and get the full member experience.
Join For FreeOne day I faced the problem with downloading a relatively large binary data file from PostgreSQL. There are several limitations to store and fetch such data (all restrictions could be found in official documentation). To resolve the problem it was suggested to find more suitable data storage.
For some internal reasons well known Amazon S3 bucket was chosen for this purpose. The choice affected the project's unit test base. It's still not possible to continue using light-weighted databases such as HSQL or H2 to implement tests. It is a key problem which we will try to resolve in this article.
Object Storage Construction
One possible solution to keep unit tests alive is to implement some mock object storage, fully compatible with S3 bucket client, on the other hand, we could use already existing object storage of this type. MinIO is a great example of pretty simple, but high-performance object storage, which is at the same time compatible with Amazon S3 (at least it is written in the documentation).
To integrate MinIO to our unit test we will use a powerful Testcontainers library written in Java. Testcontainers is a special library that supports JUnit tests and provides lightweight, throwaway instances of common databases, Selenium web browsers and anything else that can run in a Docker container. To start using this amazing library it is just necessary to have Docker and add the following dependency to our pom.xml:
xxxxxxxxxx
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.12.3</version>
<scope>test</scope>
</dependency>
Unfortunately, there is no appropriate container for our goal, but the library provides all the necessary tools to create it easily by yourself. Luckily, there is an official docker image for MinIO on DockerHub.
To create an own MinIO container it is necessary to extend GenericContainer
with custom data: DEFAULT_PORT
(MonIO documentation suggests using 9000 port), DEFAULT_IMAGE
(image name), DEFAULT_TAG
(image version).
Be attentive with tag assigning! In our example, it is used "edge" tag to support the last deployed MinIO version, but at most times it is better to fix tag and update it manually from time to time to avoid unpredictable test crashes. It is also highly recommended to provide credentials (access key, secret key) to control access to the container. Here is an example of the implementation of a custom MinIO container:
xxxxxxxxxx
public class MinioContainer extends GenericContainer<MinioContainer> {
private static final int DEFAULT_PORT = 9000;
private static final String DEFAULT_IMAGE = "minio/minio";
private static final String DEFAULT_TAG = "edge";
private static final String MINIO_ACCESS_KEY = "MINIO_ACCESS_KEY";
private static final String MINIO_SECRET_KEY = "MINIO_SECRET_KEY";
private static final String DEFAULT_STORAGE_DIRECTORY = "/data";
private static final String HEALTH_ENDPOINT = "/minio/health/ready";
public MinioContainer(CredentialsProvider credentials) {
this(DEFAULT_IMAGE + ":" + DEFAULT_TAG, credentials);
}
public MinioContainer(String image, CredentialsProvider credentials) {
super(image == null ? DEFAULT_IMAGE + ":" + DEFAULT_TAG : image);
withNetworkAliases("minio-" + Base58.randomString(6));
addExposedPort(DEFAULT_PORT);
if (credentials != null) {
withEnv(MINIO_ACCESS_KEY, credentials.getAccessKey());
withEnv(MINIO_SECRET_KEY, credentials.getSecretKey());
}
withCommand("server", DEFAULT_STORAGE_DIRECTORY);
setWaitStrategy(new HttpWaitStrategy()
.forPort(DEFAULT_PORT)
.forPath(HEALTH_ENDPOINT)
.withStartupTimeout(Duration.ofMinutes(2)));
}
public String getHostAddress() {
return getContainerIpAddress() + ":" + getMappedPort(DEFAULT_PORT);
}
public static class CredentialsProvider {
private String accessKey;
private String secretKey;
public CredentialsProvider(String accessKey, String secretKey) {
this.accessKey = accessKey;
this.secretKey = secretKey;
}
// getters
}
}
Test
Since we have a proper test container that could be used as a provider of Amazon S3 bucket object storage it is time to show an example of a simple JUnit test with it. Of course, firstly we need to configure S3 client for interacting with our container. In our case, we use the original AmazonS3Client. Therefore, to implement our unit test we need to add an extra dependence.
xxxxxxxxxx
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.60</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.60</version>
</dependency>
Here is an ordinary test for creating an S3 bucket with the specified name:
public class MinioContainerTest {
private static final String ACCESS_KEY = "accessKey";
private static final String SECRET_KEY = "secretKey";
private static final String BUCKET = "bucket";
private AmazonS3Client client = null;
public void shutDown() {
if (client != null) {
client.shutdown();
client = null;
}
}
public void testCreateBucket() {
try (MinioContainer container = new MinioContainer(
new MinioContainer.CredentialsProvider(ACCESS_KEY, SECRET_KEY))) {
container.start();
client = getClient(container);
Bucket bucket = client.createBucket(BUCKET);
assertNotNull(bucket);
assertEquals(BUCKET, bucket.getName());
List<Bucket> buckets = client.listBuckets();
assertNotNull(buckets);
assertEquals(1, buckets.size());
assertTrue(buckets.stream()
.map(Bucket::getName)
.collect(Collectors.toList())
.contains(BUCKET));
}
}
private AmazonS3Client getClient(MinioContainer container) {
S3ClientOptions clientOptions = S3ClientOptions
.builder()
.setPathStyleAccess(true)
.build();
client = new AmazonS3Client(new AWSStaticCredentialsProvider(
new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)));
client.setEndpoint("http://" + container.getHostAddress());
client.setS3ClientOptions(clientOptions);
return client;
}
}
Example code from this post can be found over on GitHub.
Further Reading
Opinions expressed by DZone contributors are their own.
Comments