Testing in Java: Part II – Writing a Fake

In the first part we talked about the domain objects and how to test a domain object.  Now it’s time to look at how to persist them to an in-memory data store for testing purposes.  We’ll be writing this in such a way that at a later date you can replace the in-memory representation with a strategy that persists the data to disk.  So, let’s jump right into the code starting with the data access object interface.

package com.laneholloway.unittestingexample.database.dao;

import com.laneholloway.unittestingexample.domain.MyItem;

import java.util.UUID;

/**
 * A simple Data Access Object
 */
public interface MyDao {
    public boolean exists(UUID guid);
    public MyItem get(UUID guid);
    public boolean save(MyItem item);
    public void delete(UUID guid);
}

Looking at the code you can easily tell that there are some simple CRUD operations and an exists command. Any datasource that we want to write the data to must implement these commands and inside the program, we should only use these commands to interact with the object. In order to facilitate the testing of the framework, I’ve created a simple in memory dao and placed it into the test directory that maven creates.

package com.laneholloway.unittestingexample.database.dao;

import com.laneholloway.unittestingexample.domain.MyItem;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * An in-memory representation of a datastore using MyDao
 */
public class MyInMemoryDao implements MyDao {
    private Map<UUID, MyItem> storedItems;

    public MyInMemoryDao() {
        this.storedItems = new HashMap<UUID, MyItem>();
    }

    @Override
    public boolean exists(UUID guid) {
        return this.storedItems.containsKey(guid);
    }

    @Override
    public MyItem get(UUID guid) {
        return this.storedItems.get(guid);
    }

    @Override
    public boolean save(MyItem item) {
        this.storedItems.put(item.getGuid(), item);
        return true;
    }

    @Override
    public void delete(UUID guid) {
        this.storedItems.remove(guid);
    }
}

The in memory dao uses a Map to hold the MyItem elements. As you can tell, the implementation is straight-forward and doesn’t pull any punches. It does exactly what it needs to do in order for us to test other parts of the system that require the use of the MyDao interface. In order for the other Maven modules to use this test implementation, we have to do a little work in Maven to expose this as a test class. In the POM file relating to the doa-interface module, we add this bit which creates a test jar file.

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Now, using this test jar we can begin to test classes that use the MyDao interface. To use this test jar you modify the POM files for all modules that need access to this code with a dependency with it’s scope set to test.

In our case, we have the MyCommonInterface class which you’ll typically see in applications to give the consumers of the code a unified API to the CRUD operations abstracting away the DAO or DAOs that might make up the data storage of the application.

package com.laneholloway.unittestingexample.database.commoninterface;

import com.laneholloway.unittestingexample.domain.MyItem;

import java.util.UUID;

/**
 * A common interface to abstract away the various DAOs and allow the consumer of the API one interface to all
 * data.
 */
public interface MyCommonInterface {
    public boolean exists(UUID guid);
    public MyItem get(UUID guid);
    public boolean save(MyItem item);
    public void delete(UUID guid);
}

I’ve also supplied a simple implementation that uses a single DAO,

package com.laneholloway.unittestingexample.database.commoninterface;

import com.laneholloway.unittestingexample.domain.MyItem;
import com.laneholloway.unittestingexample.database.dao.MyDao;

import java.util.UUID;

/**
 * A very simple common interface
 */
public class MyCommonInterfaceForOneDao implements MyCommonInterface {
    private final MyDao dao;

    public MyCommonInterfaceForOneDao(MyDao myDao) {
        this.dao = myDao;
    }

    @Override
    public boolean exists(UUID guid) {
        return this.dao.exists(guid);
    }

    @Override
    public MyItem get(UUID guid) {
        return this.dao.get(guid);
    }

    @Override
    public boolean save(MyItem item) {
        return this.dao.save(item);
    }

    @Override
    public void delete(UUID guid) {
        this.dao.delete(guid);
    }
}

You can see that in the constructor, it expects a variable of type MyDao and then uses to perform CRUD operations. In order to properly test this, we need to use the in memory implementation so we don’t have to worry about creating a database, cleaning the database, and all the other database tasks needed just to test this interface. Using the this implementation, we can create a JUnit test class like this:

package com.laneholloway.unittestingexample.database.commoninterface;

import com.laneholloway.unittestingexample.database.dao.MyDao;
import com.laneholloway.unittestingexample.database.dao.MyInMemoryDao;
import com.laneholloway.unittestingexample.domain.MyItem;
import com.laneholloway.unittestingexample.domain.MyItemImpl;
import org.junit.Before;
import org.junit.Test;

import java.util.UUID;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class MyCommonInterfaceForOneDaoTest {
    private MyCommonInterfaceForOneDao myCommonInterfaceForOneDao;

    @Before
    public void setup() {
        MyDao myDao = new MyInMemoryDao();
        myCommonInterfaceForOneDao = new MyCommonInterfaceForOneDao(myDao);
    }

    @Test
    public void can_save_item() throws Exception {
        MyItem myItem = new MyItemImpl(UUID.randomUUID(),"Test Item");
        myCommonInterfaceForOneDao.save(myItem);
        assertTrue(myCommonInterfaceForOneDao.exists(myItem.getGuid()));
    }

    @Test
    public void can_delete_item() throws Exception {
        MyItem myItem = new MyItemImpl(UUID.randomUUID(),"Test Item");
        myCommonInterfaceForOneDao.save(myItem);
        myCommonInterfaceForOneDao.delete(myItem.getGuid());
        assertFalse(myCommonInterfaceForOneDao.exists(myItem.getGuid()));
    }
}

In the setup method, you can see that MyInMemoryDao is initialized and then injected into the MyCommonInterfaceForOneDao constructor which then allows these simple unit tests to be run verifying the correct operations. And with this, we’ve wrapped up the second section of the code, creating a data access layer that abstracts the database away from the production code and will allow multiple implementations of the data store to be used with minimal issues.

In later articles, I’ll show how to use Spring to simplify these tests and the application itself. Next time, we’ll talk about the business logic and REST layers of the code.

If you have any comments, concerns, or updates I should make to this, let me know in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *