(I originally planned this to be a single article, but because of the scope decided to split it into two parts. Read the first part for the the basics of using Sun’s HttpServer to conduct functional HTTP testing. Here we revisit our functional test and rewrite it using JUnit 4.7’s new Interceptors feature.)


In my previous post, I demonstrated how to use Sun’s HttpServer API to write a functional test of an HTTP ‘conversation’.

Recall that I thought my initial solution seemed inelegant. It was verbose, with some start up and shutdown code that would have to be repeated for each test, and which I felt cluttered the actual test code.

It was also tedious, in the sense that the raw HttpHandler and HttpExchange API required us to do quite a few things manually, and unintuitively (such as having to compute and write out the length of our response before the response itself).

In this post, we’ll explore how to use the new Interceptors feature ‘quietly’ released with JUnit 4.7 to write reusable, portable pre and post-test behaviour. I’ll also exhibit a convenient HttpHandler implementation that simplifies some of the effort required in responding to HTTP requests.

Read the rest of this entry »

David Saff wrote in on Introducing MagicTest, asking why not just instantiate the variable in-line (private Foo foo = new Foo();).

Which brings me to the real reason for coming up with MagicTestActiveTest.

A code sample is worth a thousand words. Suppose we have a Spring JPA data access object:

public class WidgetDao extends JpaDaoSupport {

  public WidgetDao(final EntityManager entityManager) {

  public Widget find(long id) {
    return getJpaTemplate().find(Widget.class, id);


WidgetDao needs a JPA EntityManager provided to it at construction time. Normally, to write a unit test for WidgetDao we’d have to create our mock objects and setup our test scaffolding manually.

Using ActiveTest, however, all we need to write is:

public class WidgetDaoTest extends ActiveTest<WidgetDao> {

  private WidgetDao widgetDao;

  private EntityManager em;

  public void testFind() {
    Mockito.verify(em).find(Widget.class, 42);


I’m lazy like that.
Read the rest of this entry »

Introducing MagicTest

May 28, 2009

If you’ve written enough JUnit 4 tests, then you should be familiar with code that looks like:

public class FooTest {

  private Foo foo;

  public void setUp() {
    foo = new Foo();

  public void testBar() {

Now, how often have you wished it were possible to simply go straight to @Test, do not pass setUp(), do not have to new Foo()?

Introducing MagicTest

So I came up with MagicTest, a parameterized base class for JUnit 4 tests that’ll let us do just that. Read the rest of this entry »