Java News Brief (JNB): Migrating To JUnit 4
In the August issue of the OCI Java News Brief (JNB), Charles Sharp gave a pretty detailed prescription for migrating from JUnit 3 to JUnit 4. Besides the normal "this is what changed" material, Charles also points out some of the new features in JUnit 4.4. One of them is described thusly:
Charles Sharp: JUnit 4.4 introduces a new assert,assertThat, and some assumptions:assumeThat,assumeNotNull,assumeNoException, andassumeTrue. The 4.4 release notes give credit to Joe Walnes for theassertThatassertion mechanism. Those familiar with the jMock project will probably recognize it.The
assertThatassertions require a parameter oforg.hamcrest.Matchertype. JUnit 4.4 provides several of these Matcher classes by including a third-party package, org.hamcrest.core as well as including some in the package, org.junit.matchers. According to the release notes, this is the first time a third-party package has been shipped with JUnit. A good start on using this assertion is found in a blog post by Joe Walnes, in which he explains the rationale and intended usage ofassertThat.
That's something I would not have paid attention to. If you haven't figured out, I have a tendency to do the old thing. I would have been perfectly happy using JUnit 4 with just the @Before, @After and @Test annotations. Now I'm curious about this assertThat thing. And I wrote the following test:
import static org.hamcrest.core.AnyOf.anyOf;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class Foo {
@Test()
public void foo() {
Object o = new Object();
Object o1 = new Object();
assertThat(o, anyOf(sameInstance(o), sameInstance(o1)));
}
}
Hmmm, my unit tests can become a lot more interesting.
Got your attention? Go read the whole thing.