JUnit 4 Changes

There are some interesting changes in JUnit 4.

JUnit now uses annotations to mark test methods. No common superclass is required.

@Test public void upperBoundOfSize() throws Exception {
    ...

}

Similarly, one can annotate certain methods to be setUp/tearDown methods by annotating them with @Before and @After

Assertion methods can be statically imported using the Java 5 static import features:

import static org.junit.framework.Assert.assertEquals;

public class MyTest {
  @Test public void valueOf() {

     String value = getTheValue();
     assertEquals("fred", "expectedValue", value);
  }
}

Perhaps the nicest change is this one. Consider the following test in JUnit 3.8.1:

public void testInsufficientFunds() {
  try {
    ...
    account.withdraw(account.getBalance() + 10.00);
    fail();
  } catch (InsufficientFundsException e) {
    // expected exception
  }
}

This becomes:

@Test(expected=InsufficientFundsException)
public void testInsufficientFunds() {
  ...
  account.withdraw(account.getBalance() + 10.00);
}

At one point, Kent was asked the question, “what Mock frameworks do you like?” and his response was that his design style was such that he didn’t feel like he needed to mock out many objects, and when he did, he didn’t use a framework. He’d make his test class implement the required interface and use the test, itself, as the dependent object.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply