EasyMock does exactly what its name promises: It provides an easy way to mock objects. I never really liked the way jMock needs to be used. mockery.checking takes an ExpectationBuilder named expectations as single parameter. But this parameter is a special initialized object of type Expectations - I always had to look into the docs and count the brackets. The auto completition feature of eclipse also works bad for this way of programming. Here is a sample test using jMock:
@Test
public void testInterceptWithWrongSetSessionMethod( ) throws Throwable {
final Method[] methods = getSortedMethods();
final HibernateHelper hibernateHelper = mockery.mock(HibernateHelper.class);
final IAnnotatedMethodLocator methodLocator = mockery.mock(IAnnotatedMethodLocator.class);
final MockServiceBean serviceBean = mockery.mock(MockServiceBean.class);
final Session transactional = mockery.mock(Session.class);
final MethodInvocation invocation = mockery.mock(MethodInvocation.class);
mockery.checking(new Expectations() {
{
one(invocation).getMethod();
will(returnValue(methods[1]));
one(hibernateHelper).openTransactionalSession();
will(returnValue(transactional));
one(invocation).getThis();
will(returnValue(serviceBean));
one(methodLocator).getAnnotatedMethod(invocation, HBSISetSession.class);
will(returnValue(methods[1]));
}
});
HibernateBasedServiceInterceptor interceptor = new HibernateBasedServiceInterceptor(hibernateHelper, methodLocator);
try {
interceptor.invoke(invocation);
fail("exception expected");
} catch (ServiceException e) {
}
mockery.assertIsSatisfied();
}
And the next beautiful test method is using EasyMock:
@Test
public void testInterceptWithWrongSetSessionMethodEasyMock( ) throws Throwable {
Method[] methods = getSortedMethods();
HibernateHelper hibernateHelper = EasyMock.createMock(HibernateHelper.class);
IAnnotatedMethodLocator methodLocator = EasyMock.createMock(IAnnotatedMethodLocator.class);
MockServiceBean serviceBean = EasyMock.createMock(MockServiceBean.class);
Session transactional = EasyMock.createMock(Session.class);
MethodInvocation invocation = EasyMock.createMock(MethodInvocation.class);
EasyMock.expect(invocation.getMethod()).andReturn(methods[1]);
EasyMock.expect(hibernateHelper.openTransactionalSession()).andReturn(transactional);
EasyMock.expect(invocation.getThis()).andReturn(serviceBean);
EasyMock.expect(methodLocator.getAnnotatedMethod(invocation, HBSISetSession.class)).andReturn(methods[1]);
EasyMock.replay(hibernateHelper, methodLocator, serviceBean, transactional, invocation);
HibernateBasedServiceInterceptor interceptor = new HibernateBasedServiceInterceptor(hibernateHelper, methodLocator);
try {
interceptor.invoke(invocation);
fail("exception expected");
} catch (ServiceException e) {
}
EasyMock.verify(hibernateHelper, methodLocator, serviceBean, transactional, invocation);
}
Clean Java code using a nice and easy to use API.
Keine Kommentare:
Kommentar veröffentlichen