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.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


two × 5 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books