Automated Testing Using Gradle, JUnit and DynamoDB Local

Recently, I’ve been working on an open-source project (Todo) that uses HSQL as an in-memory embedded database. However, I’d prefer to migrate to a NoSQL database for production. Our company already uses Amazon Web Services (AWS), so I’ve decided to go with DynamoDB. Since our company is frugal, I wanted to test our code using DynamoDB Local, which is free of charge and doesn’t require an internet connection. However, unlike the automatic configuration of HSQL in a Spring Boot app, getting DynamoDB Local to run properly during tests requires additional configuration in your build script and test cases.

In this post, I’m going to outline the steps for configuring and running a local instance of DynamoDB in your JUnit tests. We’ll begin with the Gradle dependencies and tasks.

Gradle Dependencies

In the Gradle build file, configure the AWS custom repository for DynamoDB Local.

repositories {

    maven {
     //Local DynamoDB repository
     url ""

Then add the following dependencies:

dependencies {
    // AWS dynamodb
    compile group: 'com.amazonaws', name: 'aws-java-sdk-dynamodb', version: '1.11.213'

    // Use JUnit test framework
    testCompile 'junit:junit:4.12'
    //Local DynamoDB
    testCompile "com.amazonaws:DynamoDBLocal:1.+"
    //SQLite4Java, required by local DynamoDB
    testCompile group: 'com.almworks.sqlite4java', name: 'sqlite4java', version: '1.0.392'    


Gradle Tasks

Next, add the following tasks to the Gradle build file:

//Copy SQLite4Java dynamic libs
task copyNativeDeps(type: Copy) {
    from(configurations.compile + configurations.testCompile) {
        include '*.dll'
        include '*.dylib'
        include '*.so'
    into 'build/libs'

test {
    dependsOn copyNativeDeps
    systemProperty "java.library.path", 'build/libs'


JUnit Test Case

In your test case, I recommend configuring and running DynamoDB Local before any tests are executed and shutting it down after the tests have completed. You’ll also want to create your tables before executing your tests. This can be achieved by annotating a public static method in your test class with @BeforeClass.

Note: sServer and sClient are static fields in your test class.

public static void runDynamoDB() {

  //Need to set the SQLite4Java library path to avoid a linker error
  System.setProperty("sqlite4java.library.path", "./build/libs/");

  // Create an in-memory and in-process instance of DynamoDB Local that runs over HTTP
  final String[] localArgs = { "-inMemory" };

  try {
	sServer = ServerRunner.createServerFromCommandLineArgs(localArgs);

  } catch (Exception e) {


private static void createAmazonDynamoDBClient() {
  sClient = AmazonDynamoDBClientBuilder.standard()
	        .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))

private static void createMyTables() {
	//Create task tables
  DynamoDBMapper mapper = new DynamoDBMapper(sClient);
  CreateTableRequest tableRequest = mapper.generateCreateTableRequest(MyItemOne.class);
  tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));

  tableRequest = mapper.generateCreateTableRequest(MyItemTwo.class);
  tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));

  tableRequest = mapper.generateCreateTableRequest(MyItemThree.class);
  tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));

Then after the tests have completed, you’ll want to ensure that the database is shutdown by by annotating a public static method in your test class with @AfterClass.

public static void shutdownDynamoDB() {
  if(sServer != null) {
     try {
     } catch (Exception e) {

I hope these steps help you to more easily implement local automated tests of your DynamoDB code. Let me know if you have any feedback.


Stack Overflow,

Stack Overflow,

Testing Excellence,

Automated Testing Using Gradle, JUnit and DynamoDB Local

RESTful Serialization with Flexjson

XML is too fat for a mobile RESTful API. Therefore, I’m using JavaScript Object Notation (JSON) to exchange data between mobile devices and a cloud service I’m developing. My server environment is J2EE-based, so I chose Flexjson to serialize Java object fields as JSON. This post is a quick overview of my implementation and a lesson learned.

Flexjson is a lightweight Java library that enables object filtering during serialization. If you have a complex object model, serializing the entire object graph is undesirable. Flexjson allows you to pick and choose which objects or fields to serialize.

Here’s simple example of excluding a password field in serialized JSON.

String result =
         new JSONSerializer().
         exclude("password").serialize("user", this);
Client's JSON result
   "user": {
   "class": "com.mycompany",
   "email": "",
   "firstName": "John",
   "lastName": "Doe",
   "phone": "555-1212"

The shallow deserialization is limited to: String, Date, Number, Boolean, Character, Enum, Object and null. Subclasses of Object will be serialized except for Collection or Arrays. Consequently, if the deserializer is unable to construct the object, an exception will be thrown.

All objects are built using an ObjectFactory during deserialization and each object must have a constructor that takes no arguments. Users can write their own factories and the library comes with many factories for types such as bytes, characters, dates, and so on. However, an integer object factory is nonexistent. Here’s mine:

public class IntObjectFactory implements ObjectFactory {

	/* (non-Javadoc)
	 * @see flexjson.ObjectFactory#instantiate(flexjson.ObjectBinder,

	public Object instantiate(ObjectBinder context,
                                  Object value,
                                  Type targetType,
                                  Class targetClass) {
		 if( value instanceof Number ) {
	            return ((Number)value).intValue();
	        } else {
	            throw context.

It was so easy to write, I’m not sure why is wasn’t included in the shipped version.

Lastly, here’s how to use the factory during deserialization:

JSONDeserializer<Map<String, List<SomeObject>>> deserializer =
       new JSONDeserializer<Map<String, List<SomeObject>>>();

Map<String, List<SomeObject>> members =
       new IntObjectFactory()).deserialize(returnValue);

For more info check out the Flexjson home page here:

RESTful Serialization with Flexjson

Java SSL: How to accept a self-signed certificate

I’ve been working on a RESTful API for use on computers and mobile devices. I have a JUnit test case that connects to the URLs and reads the responses. Given the nature of the data being transferred back and forth, I enabled SSL on the web server using a self-signed certificate I generated using Java’s keytool.

keytool -genkey -alias <hostname> -keyalg RSA

This is where my problems began. My test case is using HTTP, so I needed to refactor it to use the HTTPS protocol. Unbeknownst to me, accepting SSL connections from self-signed certificates is non-trivial, especially if you want to do it right. There is copious advice on the inter-web about how to accept any certificate. I’m not keen on that approach; therefore, I set out to find the correct way.

Without a decent Java security reference handy, I surfed the internet for answers. I found partial code snippets on stackoverflow and Example Depot. In a nutshell, I found that you need an instance of a SSLSocketFactory to set in a HttpsURLConnection. Here’s how:

// Load the keystore in the user's home directory
File file = new File(System.getProperty("user.home") + File.separatorChar + ".keystore");
FileInputStream fis = null;
KeyStore keyStore = null;

fis = new FileInputStream(file);
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(fis, keystorePassword.toCharArray());

TrustManagerFactory tmf;

tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);

//Get an instance of the socket factory
SSLSocketFactory sslFactory = ctx.getSocketFactory();

HttpsURLConnection connection = null;
url = new URL(newURLString);

connection = (HttpsURLConnection)url.openConnection();

//set the socket factory in the connection


Tip: Remember the alias created in the keytool must be the hostname of the server. Otherwise, an exception will be thrown on the client: No name matching <alias> found
Java SSL: How to accept a self-signed certificate