ActiveTest – Instantiation, mocking, and injection for the lazy

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 {

  @Autowired
  public WidgetDao(final EntityManager entityManager) {
    setEntityManager(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;

  @Mock
  private EntityManager em;

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

}

I’m lazy like that.
Continue reading

Introducing MagicTest

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

public class FooTest {

  private Foo foo;

  @Before
  public void setUp() {
    foo = new Foo();
  }

  @Test
  public void testBar() {
    assertTrue(foo.bar());
  }
}

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. Continue reading