What I liked more about EasyMock is the ease when creating mocks without much hassle. For example I had a test written in this way:
/**
* Check that proxy works when on-demand instantiation creates
* an object which implement the right interface.
*/
public void testProxyWorksOk() {
Mock mockCfgElement = mock( IConfigurationElement.class );
mockCfgElement.expects( once() )
.method( "createExecutableExtension" )
.with( eq( ExtensionsProxyFactory.CLASS_ATTR ) )
.will( returnValue( new ProxyWannabe() ) );
IProxyWannabe proxy = proxyFactory.getProxy(
IProxyWannabe.class,
(IConfigurationElement) mockCfgElement.proxy() );
assertEquals( 0, proxy.getDummy() );
proxy.costlyMethod1();
assertEquals( 1, proxy.getDummy() );
assertNotNull( proxy.costlyMethod2() );
}
This uses the typical JMock-pattern for writing expectations using some kind of specific API for testing (expects( once() ).method( "
- Write the expectation(s) for your mock object (what methods are to be called, with which parameters and what values are to be returned).
- Get an object implementing the interface you want your object to be tested with.
- Run the method you want to test with this mock.
- Verify the expectations.
The same test with EasyMock becomes:
public void testProxyWorksOk() throws Exception {
IConfigurationElement mockCfgElement = createMock( IConfigurationElement.class );
expect( mockCfgElement.createExecutableExtension( ExtensionsProxyFactory.CLASS_ATTR ) )
.andReturn( new ProxyWannabe() );
replay( mockCfgElement );
IProxyWannabe proxy = proxyFactory.getProxy( IProxyWannabe.class, mockCfgElement );
assertEquals( 0, proxy.getDummy() );
proxy.costlyMethod1();
assertEquals( 1, proxy.getDummy() );
assertNotNull( proxy.costlyMethod2() );
verify( mockCfgElement );
}
You will notice:
- The mock factory method returns an interface compatible with the one we want to mock (IConfigurableElement, in this case): JMock creates a proxy object (instance of type Mock).
- Writing the expectation is pretty straightforward (and less bloated).
- Verification must be performed explicitely.
Some resources for the ones who have lived in Outer Space and don't know about mock objects:
Let's see how JMock2 will cope with the challenge ...
No comments:
Post a Comment