A good, lazy way to write tests

Testing. I’ve been thinking a lot about testing recently. As part of code reviews I’ve done for various projects, I’ve seen thousands of lines of untested code. This is not just a case of test coverage statistics pointing this out, it’s more a case of there not being any tests at all in this projects. And the two reason I keep hearing for this sad state of affairs? “We don’t have time”, swiftly followed by “We’ll do it when we’ve finished the code”.

What I present here is not a panacea for testing. It covers unit testing, and specifically, unit testing of interfaces. Interfaces are good things. Interfaces define contracts. Interfaces, regardless of how many implementations they have, can be tested easily and with very little effort. Let’s see how, using this class structure as an example.
 
 
fd98ced9
CustomerService is our interface. It has two methods, to keep the example simple, and is described below. Note the javadoc – this is where the contract is described.

public interface CustomerService
{
    /**
     * Retrieve the customer from somewhere.
     * @param userName the userName of the customer
     * @return a non-null Customer instance compliant with the userName
     * @throws CustomerNotFoundException if a customer with the given user name can not be found
     */
    Customer get(String userName) throws CustomerNotFoundException;

    /**
     * Persist the customer.
     * @param customer the customer to persist
     * @return the customer as it now exists in its persisted form
     * @throws DuplicateCustomerException if a customer with the user name already exists
     */
    Customer create(Customer customer) throws DuplicateCustomerException;
}

As we can see from the diagram, we have two implementations of this class, RemoteCustomerService and CachingCustomerService. The implementations of these are not shown, because they don’t matter. How can I say this? Simple – we are testing the contract. We write tests for every method in the interface, along with every permutation of the contract. For example, for get() we need to test what happens when a customer with the given user name is present, and what happens when it isn’t present.

public abstract class CustomerServiceTest
{
    @Test
    public void testCreate()
    {
        CustomerService customerService = getCustomerService();
        Customer customer = customerService.create(new Customer("userNameA"));

        Assert.assertNotNull(customer);
        Assert.assertEquals("userNameA",
                            customer.getUserName());
    }

    @Test(expected = DuplicateCustomerException.class)
    public void testCreate_duplicate()
    {
        CustomerService customerService = getCustomerService();
        Customer customer = new Customer("userNameA");
        customerService.create(customer);
        customerService.create(customer);
    }

    @Test
    public void testGet()
    {
        CustomerService customerService = getCustomerService();
        customerService.create(new Customer("userNameA"));
        Customer customer = customerService.get("userNameA");

        Assert.assertNotNull(customer);
        Assert.assertEquals("userNameA",
                            result.getUserName());
    }

    @Test(expected = CustomerNotFoundException.class)
    public void testGet_noUser()
    {
        CustomerService customerService = getCustomerService();
        customerService.get("userNameA");
    }

    public abstract CustomerService getCustomerService();
}

We now have a test for the contract, and at no point have we mentioned any of the implementations. This means two things:

  • We don’t need to duplicate the tests for each and every implementation. This is a Very Good Thing.
  • None of the implementations are being tested. We can correct this by adding one test class per implementation. Since each test class will be almost identical, I’ll just show the test of RemoteCustomerService.
public class RemoteCustomerServiceTest extends CustomerServiceTest
{
    public CustomerService getCustomerService()
    {
        return new RemoteCustomerService();
    }
}

And that’s it! We now have a very simple way to test multiple implementations of any interface by putting in the hard work up front, and reducing the effort of testing new implementations to a single, simple method.
 

Reference: A good, lazy way to write tests from our JCG partner Steve Chaloner at the Objectify blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


7 + five =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close