I tried out the new JUnit @Rule feature to setup an IMocksControl to automatically create and verify my mocks. It turns out that it works pretty well. The syntax ends up looking like this:
public class MyTest {
@Rule public EasyMockRule mocks = new EasyMockRule();
@Mock InterfaceToMock theMock;
@CreateWithMocks SomeObject objectToTest;
@Test
public void testStuff() {
expect(theMock.doStuff()).andReturn("stuff");
mocks.replay();
assertEquals("stuff", objectToTest.doIt());
}
}
There are a number of interesting things to notice.
There are a few special cases that it handles
1. If you don't call mocks.replay(), it won't do mocks.verify()
2. It always does mocks.reset() before each test (because mocks aren't recreated for each test)
3. If you have multiple constructors, you can use @CreateWithMocks(constructor={InterfaceToMock.class}) to identify which constructor to use
4. If a constructor parameter has no matching mock, null is passed in.
5. You can specify the type of mocks by using @Rule public EasyMockRule mocks = new EasyMockRule(createNiceControl());
Another nice point is that EasyMockRule runs before and after the @Before and @After methods. This way you can put things in @Before and @After and all the mocks will already be created for you.
Patch for EasyMock 3.0, implementing EasyMockRule