General Musing

blaze your trail

Posts Tagged ‘junit

Mocking up your objects with EasyMock #test #junit #xp #tdd

leave a comment »

I’ve recently been using EasyMock to create mock objects to pass in my JUnit tests, and I often find that I often mock up objects for private members which are auto-wired or injected by the platform, and in some cases are unrelated to the code I unit testing. Usually it is too expensive to run a full environment of middleware for testing, and it is also necessary to test the exception handling code which will most likely not be called unless it is specifically mocked.

So I wrote the following function to insert a mock object into a private member:

public <T> T insertPrivateField(Object instance, Class<?> targetClass,
        String targetFieldName,
        Class<T> mockedClass) {
    T mockedObject = null;
     try {
        Class<?> clazz = Class.forName(targetClass.getCanonicalName());
        Field field = clazz.getDeclaredField(targetFieldName);

        mockedObject = EasyMock.createMock(mockedClass);
        field.set(instance, mockedObject);
        } catch (Exception e) {
         log.error(e.getMessage(), e); // logs exception with log4j
        fail(e.getMessage()); // junit failure generated
     return mockedObject;

Have fun with it.


Written by Daniël W. Crompton (webhat)

August 15, 2011 at 1:41 pm

Posted in programming

Tagged with , , , , , , ,

%d bloggers like this: