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 MagicTest—ActiveTest.

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 »


Get every new post delivered to your Inbox.