Mockito

A few weeks ago, I started using Mockito. Mockito is a mocking framework for Java.

What mockito is able to do:
– mocking interfaces and abstract classes
– mocking concrete classes
– spy real objects

(http://code.google.com/p/mockito)

I liked mockito so much that I decided to present it to you…

Why mockito?
There exist a lot of mocking frameworks for Java. For example:  JMock, EasyMock, RMock, etc.. I choose  Mockito, because  in my opinion Mockito is very easy to use because:
– There is no need to create a mocking factory or a control to create a mock.
– If methods were called on the mock, you don’t have to capture this first an then let it replay. Just create a mock, let the testcode run and check if the interactions met your expectations.
– Stubbing is more intuitive than by other mocking frameworks.
– The code really reads like spoken language.

Now I will show you some samples. The following interface will be used:

public interface ISample {
   void setName(String name);
   String getName();
}

How to create a mock.

Sample sample = Mockito.mock(ISample.class);

This mock is fully usable. You can set the name and call getName. (Sure the return value will just be  ‘null’). Mockito will not throw exceptions by default.

Stub some methods.
If you don’t like just ‘null’ as return value you can do something like this.

Simple return value

Mockito.when(sample.getName()).thenReturn("stubbedName");

Throw an exception

Mockito.when(sample.getName()).thenThrow(new IllegalStateException());

Wow I do not even need to explain what the mock does since the code is so readable.

Verify #-calls

sample.setName("foo");
Mockito.verify(sample).setName("foo");

or if it just must be called

Mockito.verify(sample).setName(Mockito.anyString());

Verify call order
If  you have to check the order of method calls there is the InOrder of Mockito. Just verify what you want.

sample.setName("foo");
sample.setName("bar");
InOrder order = Mockito.inOrder(sample);
order.verify(sample).setName("foo");
order.verify(sample).setName("bar");

How to stub (spy) a part of an object
All of these verifications can be done with a spy too.

final ISample sample = new Sample();
final ISample spySample = Mockito.spy(sample);
spySample.setName("foo");
final InOrder order = Mockito.inOrder(spySample);
order.verify(spySample).setName("foo");

Import
All the methods I called on Mockito can be used with a static import. This way you don’t have to write Mockito.xyz(). And you don’t have to extend anything.
The samples I’ve shown in this post are just the top of the iceberg. Download it and check it out.

About the author

Adrian Elsener

1 comment

Recent Posts