Automatic mock creation with JUnit & Mockito

February 19th, 2009

Mockito is really a great mocking framework. It is based on a powerful stubbing and verification mecanism. Using it is as simple as this:

 import static org.mockito.Mockito.*;

 List mockedList = mock(List.class);

 mockedList.add("one");
 mockedList.clear();

 verify(mockedList).add("one");
 verify(mockedList).clear();

A handy tool provided by Mockito is a custom JUnit runner that automatically creates mock for fields tagged with @Mock annotation:

@RunWith(MockitoJUnit44Runner.class)
public class ArticleManagerTest {
    @Mock private ArticleCalculator calculator;
    @Mock private ArticleDatabase database;
    @Mock private UserProvider userProvider;

    private ArticleManager manager;

In our team, we came up with an even simpler solution. All mock names should start with mock to ease test code readability. So we coded a custom Runner that doesn’t need the @Mock annotation.

@RunWith(AutoMockRunner.class)
public class ArticleManagerTest {
    private ArticleCalculator mockCalculator;
    private ArticleDatabase mockDatabase;
    private UserProvider mockUserProvider;

    private ArticleManager manager;

Here is the runner implementation:

public class AutoMockRunner extends BlockJUnit4ClassRunner {
  public AutoMockRunner(Class< ?> clazz) throws InitializationError {
    super(clazz);
  }

  @Override
  protected Object createTest() throws Exception {
    Object clazz = super.createTest();

    for (Class< ?> c = clazz.getClass(); c != Object.class; c = clazz.getSuperclass()) {
      scan(testClass, c);
    }

    return clazz;
  }

  private static void scan(Object testClass, Class< ?> clazz) {
    for (Field field : clazz.getDeclaredFields()) {
      if (field.getName().startsWith("mock")) {
        Object mock = Mockito.mock(field.getType(), field.getName());

        try {
          if (field.isAccessible()) {
            field.set(testClass, mock);
          } else {
            field.setAccessible(true);
            try {
              field.set(testClass, mock);
            } finally {
              field.setAccessible(false);
            }
          }
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        }
      }
    }
  }
}

Blog , ,

We can’t write expressive code

January 12th, 2009

Ever since there are programming languages, good programmers have tried to write code that is expressive enough to be understood and maintained. However, put two good programmers face to face and chances are they might agree on what expressive mean but they won’t agree on how to do it.

haskel

Read more…

Blog , , ,

Banking problem explained

January 7th, 2009

This was sent to me by email. I don’t know the source. It might be this blog as pointed by Google.
Dead Donkey

Young Chuck moved to Texas and bought a donkey from a farmer for $100.00.

The farmer agreed to deliver the donkey the next day.

The next day he drove up and said, ‘Sorry son, but I have some bad news, the donkey died.’

Chuck replied, ‘Well, then just give me my money back.’

The farmer said, ‘Can’t do that. I went and spent it already.’

Chuck said, ‘OK, then, just bring me the dead donkey.’

The farmer asked, ‘What ya gonna do with him?

Chuck said, ‘I’m going to raffle him off.’

The farmer said ‘You can’t raffle off a dead donkey!’

Chuck said, ‘Sure I can Watch me. I just won’t tell anybody he’s dead.’

A month later, the farmer met up with Chuck and asked, ‘What happened with that dead donkey?’

Chuck said, ‘I raffled him off. I sold 500 tickets at two dollars apiece and made a profit of $898.00.’

The farmer said, ‘Didn’t anyone complain?’

Chuck said, ‘Just the guy who won. So I gave him his two dollars back.’

Chuck now works for Goldman Sachs.

Blog