Monday, 26 April 2010

Static Imports

I've been working with Java for a long time, since version 1.2 in fact. I suppose it's human nature to stick with things we know and, as a consequence, and despite reviewing the change logs when they come out, I sometimes find myself becoming aware of things in new versions of Java that I was blissfully ignorant of.

Today was an example. I was writing some JUnit test scripts and using my usual approach with assertions:

import org.junit.Assert;
import org.junit.Test;

public class ConversionUtilTest {

    @Test
    public void testMetresToFeet() {
        Assert.assertEquals(0, ConversionUtil.metresToFeet(0));
        Assert.assertEquals(3117, ConversionUtil.metresToFeet(950));
        Assert.assertEquals(3114, ConversionUtil.metresToFeet(949));
        Assert.assertEquals(3110, ConversionUtil.metresToFeet(948));
    }

    ...

}

The example I was working on was more involved than that, and had many more assertions going on of different types: assertEquals(), assertTrue(), etc. But you get the idea.

I couldn't remember how to test for an exception with a JUnit annotation, so I searched for an example. Here's how you do it, by the way:

    @Test(expected=java.lang.IllegalArgumentException.class)
    public void testMetresToFeetInvalid() {
        ConversionUtil.metresToFeet(-1);
    }

And that's when I discovered an example with static imports, meaning the above can be rewritten more succinctly like this:

import static org.junit.Assert.assertEquals;
import static mypackage.ConversionUtil.*;
import org.junit.Test;

public class ConversionUtilTest {

    @Test
    public void testMetresToFeet() {
        assertEquals(0, metresToFeet(0));
        assertEquals(3117, metresToFeet(950));
        assertEquals(3114, metresToFeet(949));
        assertEquals(3110, metresToFeet(948));
    }

    ...

}

Not an earth-shattering revelation, and I wouldn't want to overuse it, but it does save a bit of typing in unit tests where the assertions become repetitive. Makes it more readable too, without all those class names.

You can read more about static imports in the Java 1.5 documentation, in particular when it's a good idea to use them, and when not:

Java 1.5 Static Import

Given the repetition and naming of methods in the org.junit.Assert class, I think I'd even be happy with a wildcard import in most of my test classes, i.e. import org.junit.Assert.*;.

No comments:

Followers