Traditionally unit testing is performed with a class being injected with mocks for its dependencies, so testing is focused just on the behaviours of the class under consideration.

While this is effective for “simple” dependent APIs that may only have a few behaviours, for complex resources such as databases, web service APIs such as DynamoDB, etc it can make sense to unit test using a “fast” implementation of the real resource. By “fast” here we mean quick to setup and tear down so that we can concentrate our effort on the behaviours of the class being tested.
Modern development is tied closely to cloud native APIs such as AWS. We can use a “fast” stub of AWS service with LocalStack deployed on docker. This gives us in memory, localhost based AWS services for most of the available APIs.

How to do this using Java and Maven
Using our oss-maven-standards build system we have enabled optional Docker style unit testing using Surefire under Maven. An example layout with docker compose configuration, etc can be seen in the java-lambda-poc module.
Use the any of our parent POMs as your maven archetype.
Set your pom.xml’s parent to one of our archetypes to get docker support. For example, when building a java lambda:
<parent> <groupId>com.limemojito.oss.standards</groupId> <artifactId>java-lambda-development</artifactId> <version>15.2.7</version> <relativePath/> </parent>
Enable docker for unit test mode
This is done in the properties section of the pom.xml
<properties> ... <!-- Test docker unit test... --> <docker.unit.test>true</docker.unit.test> ... </properties>
For Spring Boot testing, set active profile to “integration-test”
We are using our S3Support test utilities to build a set of S3 resources around our unit test. These automatically configure LocalStack when the configuration is imported as below.
@ActiveProfiles("integration-test") @SpringBootTest(classes = S3SupportConfig.class) public class S3DockerUnitTest { @Autowired private S3Support s3;
Write your unit test
Now we can write a unit test that is backed by LocalStack’s S3 implementation in docker when the test runs:
@Test public void shouldDoThingsWithS3AsAUnitTest() { s3.putData(s3Uri, "text/plain", "hello world".getBytes(UTF_8)); assertThat(s3.keyExists(s3Uri)).withFailMessage("Key %s is missing", s3Uri) .isTrue(); }
Full Source Example
https://github.com/LimeMojito/oss-maven-standards/tree/master/development-test/jar-lambda-poc