Thursday, May 28, 2009

Mockito is first mock framework you should consider

Having been stuck on jdk 1.4 for the last 3 years it came as something akin to a coming of age to step into modern java; and a most satisfying revelation has been mockito.

If you have used easy mock in the past you will be very pleased and probably quite excited when you encounter and start using mockito. It is totally awesome.

It is simple, intuitive, terse and has some very powerful features. It will gracefully handle almost all of your mocking needs. For example, it is possible to stub out selected methods on a live object.

To give you an example of mockito in action, to whet your appetite, here is a code snippet.

ConfigParams params = Mockito.mock(ConfigParams.class);
when(params.getInt(ConfigParamKey.AGENT_MATCH_TIMEOUT)).thenReturn(99);


So, it's fairly self explanatory, when the method getInt is called with the parameter ConfigParamKey.AGENT_MATCH_TIMEOUT then the mock should return 99.

In case you were wondering how this all happens, generics are playing an important role - thus the reason why it is only available on jdk5+

As in EasyMock and JMock you can verify that the method was called.

It is probably worth pointing out that Mockito tries to be less strict with its mocking than other mock frameworks. For example, the default mock you get will accept any call - and unless you specifically verify (which you can do), not calling the method will not cause a test failure.call

See the web site for more information, downloads and demos.

No comments: