ActiveTest – Instantiation, mocking, and injection for the lazy

May 30, 2009

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.

Under the hood

ActiveTest uses the ParameterizedType hack to discover the actual type parameter (the class under test) at run-time.

It then inspects the test class instance for any fields annotated with Mockito’s @Mock, and has Mockito construct those mock objects. At the same time, each mock object is registered into an internal Spring auto-wiring capable bean factory.

Finally, that Spring bean factory is itself used to construct an instance of the class under test. Because we’re using Spring itself to perform construction, we fully support field, setter or construction-based @Autowired injection of dependencies.

See the full source code of ActiveTest on the dirty-mockito project site on Google Code

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: