Sonntag, 27. Oktober 2013

DRY unit tests

Unit tests are written in the same quality as the production source code therefore, they follow the DRY principle. To achieve this goal it is sometimes necessary to enhance unit tests with a new runner for the JUnit tooling. JUnitParams adds a new runner to provide easier and more readable unit tests. By using JUnitParams you have to write less source code for your unit tests through short cuts like the $(…) method. The following example compares JUnitParams with a regular written unit test.

Class under test

public class Message {

    private final String message;

    public Message(final String message) {

        if(null == message || message.isEmpty()) {

            throw new IllegalArgumentException("Message is null or empty!");
        }

        this.message = message;
    }

    public String getMessage() {

        return message;
    }
}

Regular unit test

public class MessageTest {

    @Test
    public void testMessageHello() {

        final Message message = new Message("Hello");

        Assert.assertEquals("Hello", message.getMessage());
    }

    @Test
    public void testMessageWorld() {

        final Message message = new Message("World");

        Assert.assertEquals("World", message.getMessage());
    }

    @Test(expected= IllegalArgumentException.class)
    public void testMessageIsNull() {

        final Message message = new Message(null);
    }

    @Test(expected= IllegalArgumentException.class)
    public void testMessageIsEmpty() {

        final Message message = new Message("");
    }
}

Unit test with JUnitParams

@RunWith(JUnitParamsRunner.class)
public class MessageParameterizedTest {

  private static final Object[] getMessageValue() {

        return $(

            $("Hello"),
            $("World")
        );
    }

    private static final Object[]  getInvalidMessageValue() {
        return new String [] [] {{null},{""}};
    }

    @Test
    @Parameters(method="getMessageValue")
    public void testValidMessages(final String messageParam) {

        final Message message = new Message(messageParam);

        Assert.assertEquals(messageParam, message.getMessage());
    }

    @Test(expected=IllegalArgumentException.class)
    @Parameters(method="getInvalidMessageValue")
    public void testInvalidMessages(final String messageParam) {

        final Message message = new Message(messageParam);
    }
}


Der Rechtshinweis des Java Blog für Clean Code Developer ist bei der Verwendung und Weiterentwicklung des Quellcodes des Blogeintrages zu beachten.