Twitter github

JUnit4 @Rule’s Rule

Maybe I’ve been under a rock as of late, but I’ve been writing some tests as of late and came across a nifty little feature in JUnit4 called Rules while needing to verify a certain exception was being thrown. For example, let’s say we needed to verify that something threw an IAE…

public class MyTest {
  @Rule
  public ExpectedException exception = ExpectedException.none();
 
  @Test
  public void willThrowIAE() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("omg bad arguments");
    // do crap that will throw an IAE
  }
}

This is just the tip of the iceberg with what you can do with rules. There’s also a rule (TemporaryFolder) for creating temporary folders that are guaranteed to be deleted after the test is run. On top of that, it’s pretty easy to create your own rules if you need to modify test behavior to suit your needs.

In the end, it’s always fun to discover something new and useful in a tool you’ve been using for awhile.