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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. An Efficient Object Storage for JUnit Tests

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.

Aleksandr Kirilenko user avatar by
Aleksandr Kirilenko
·
Jan. 29, 20 · Analysis
Like (3)
Save
Tweet
Share
11.60K Views

Join the DZone community and get the full member experience.

Join For Free

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

You may also like: Integrating With File Storage vs. Object Storage

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:

XML
xxxxxxxxxx
1
 
1
<dependency>
2
    <groupId>org.testcontainers</groupId>
3
    <artifactId>testcontainers</artifactId>
4
    <version>1.12.3</version>
5
    <scope>test</scope>
6
</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:

Java
xxxxxxxxxx
1
46
 
1
public class MinioContainer extends GenericContainer<MinioContainer> {
2
3
    private static final int DEFAULT_PORT = 9000;
4
    private static final String DEFAULT_IMAGE = "minio/minio";
5
    private static final String DEFAULT_TAG = "edge";
6
7
    private static final String MINIO_ACCESS_KEY = "MINIO_ACCESS_KEY";
8
    private static final String MINIO_SECRET_KEY = "MINIO_SECRET_KEY";
9
10
    private static final String DEFAULT_STORAGE_DIRECTORY = "/data";
11
    private static final String HEALTH_ENDPOINT = "/minio/health/ready";
12
13
    public MinioContainer(CredentialsProvider credentials) {
14
        this(DEFAULT_IMAGE + ":" + DEFAULT_TAG, credentials);
15
    }
16
17
    public MinioContainer(String image, CredentialsProvider credentials) {
18
        super(image == null ? DEFAULT_IMAGE + ":" + DEFAULT_TAG : image);
19
        withNetworkAliases("minio-" + Base58.randomString(6));
20
        addExposedPort(DEFAULT_PORT);
21
        if (credentials != null) {
22
            withEnv(MINIO_ACCESS_KEY, credentials.getAccessKey());
23
            withEnv(MINIO_SECRET_KEY, credentials.getSecretKey());
24
        }
25
        withCommand("server", DEFAULT_STORAGE_DIRECTORY);
26
        setWaitStrategy(new HttpWaitStrategy()
27
                .forPort(DEFAULT_PORT)
28
                .forPath(HEALTH_ENDPOINT)
29
                .withStartupTimeout(Duration.ofMinutes(2)));
30
    }
31
32
    public String getHostAddress() {
33
        return getContainerIpAddress() + ":" + getMappedPort(DEFAULT_PORT);
34
    }
35
36
    public static class CredentialsProvider {
37
        private String accessKey;
38
        private String secretKey;
39
        public CredentialsProvider(String accessKey, String secretKey) {
40
            this.accessKey = accessKey;
41
            this.secretKey = secretKey;
42
        }
43
44
        // getters
45
    }
46
}


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.

XML
xxxxxxxxxx
1
10
 
1
<dependency>
2
    <groupId>com.amazonaws</groupId>
3
    <artifactId>aws-java-sdk-s3</artifactId>
4
    <version>1.11.60</version>
5
</dependency>
6
<dependency>
7
    <groupId>com.amazonaws</groupId>
8
    <artifactId>aws-java-sdk</artifactId>
9
    <version>1.11.60</version>
10
</dependency>


Here is an ordinary test for creating an S3 bucket with the specified name:

Java
x
50
 
1
public class MinioContainerTest {
2
3
    private static final String ACCESS_KEY = "accessKey";
4
    private static final String SECRET_KEY = "secretKey";
5
    private static final String BUCKET = "bucket";
6
7
    private AmazonS3Client client = null;
8
9
    @After
10
    public void shutDown() {
11
        if (client != null) {
12
            client.shutdown();
13
            client = null;
14
        }
15
    }
16
17
    @Test
18
    public void testCreateBucket() {
19
        try (MinioContainer container = new MinioContainer(
20
                new MinioContainer.CredentialsProvider(ACCESS_KEY, SECRET_KEY))) {
21
22
            container.start();
23
            client = getClient(container);
24
            Bucket bucket = client.createBucket(BUCKET);
25
            assertNotNull(bucket);
26
            assertEquals(BUCKET, bucket.getName());
27
28
            List<Bucket> buckets = client.listBuckets();
29
            assertNotNull(buckets);
30
            assertEquals(1, buckets.size());
31
            assertTrue(buckets.stream()
32
                    .map(Bucket::getName)
33
                    .collect(Collectors.toList())
34
                    .contains(BUCKET));
35
        }
36
    }
37
38
    private AmazonS3Client getClient(MinioContainer container) {
39
        S3ClientOptions clientOptions = S3ClientOptions
40
                .builder()
41
                .setPathStyleAccess(true)
42
                .build();
43
44
        client = new AmazonS3Client(new AWSStaticCredentialsProvider(
45
                new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)));
46
        client.setEndpoint("http://" + container.getHostAddress());
47
        client.setS3ClientOptions(clientOptions);
48
        return client;
49
    }
50
}


Example code from this post can be found over on GitHub.


Further Reading

Deploying Big Data Workloads on Object Storage Without Performance Penalty

Object Store Connector in Mule ESB

Working With Object Store in Mule, Part 1

unit test Object storage Object (computer science) AWS JUnit Docker (software) Big data

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 5 Steps for Getting Started in Deep Learning
  • gRPC on the Client Side
  • Automated Testing With Jasmine Framework and Selenium
  • Collaborative Development of New Features With Microservices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: