Mockito in six easy examples

Mockito is a fantastic mock library for Java. I’m fascinated by how easy it is to use, compared to other things out there both in the Java and .NET world. Here is everything you need to know to get started in six really easy examples.

First of all, get mockito from http://mockito.org/. Almost everything really interesting can be imported with the org.mockito.Mockito class (or a static import of its methods, which I’ll use in this post). So let’s get right into it.

To create a stub (or a mock), use mock(class). Then use when(mock).thenReturn(value) to specify the stub value for a method. If you specify more than one value, they will be returned in sequence until the last one is used, after which point the last specified value gets returned. (So to have a method return the same value always, just specify it once). For example:

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import java.util.Iterator;
import org.junit.Test;
....
	@Test
	public void iterator_will_return_hello_world(){
		//arrange
		Iterator i=mock(Iterator.class);
		when(i.next()).thenReturn("Hello").thenReturn("World");
		//act
		String result=i.next()+" "+i.next();
		//assert
		assertEquals("Hello World", result);
	}

This example creates a mock iterator and makes it return “Hello” the first time method next() is called. Calls after that return “World”. Then we can run normal assertions.

Stubs can also return different values depending on arguments passed into the method. For example:

	@Test
	public void with_arguments(){
		Comparable c=mock(Comparable.class);
		when(c.compareTo("Test")).thenReturn(1);
		assertEquals(1,c.compareTo("Test"));
	}

This creates a stub Comparable object and returns 1 if it is compared to a particular String value (“Test” in this case). If the method has arguments but you really don’t care what gets passed or cannot predict it, use anyInt() (and alternative values for other types). For example:

	@Test
	public void with_unspecified_arguments(){
		Comparable c=mock(Comparable.class);
		when(c.compareTo(anyInt())).thenReturn(-1);
		assertEquals(-1,c.compareTo(5));
	}

This stub comparable returns -1 regardless of the actual method argument. With void methods, this gets a bit tricky as you can’t use them in the when() call. The alternative syntax is doReturn(result).when(mock_object).void_method_call(); Instead of returning, you can also use .thenThrow() or doThrow() for void methods. For example:

	@Test(expected=IOException.class)
	public void OutputStreamWriter_rethrows_an_exception_from_OutputStream() 
		throws IOException{
		OutputStream mock=mock(OutputStream.class);
		OutputStreamWriter osw=new OutputStreamWriter(mock);
		doThrow(new IOException()).when(mock).close();
		osw.close();
	}

This example throws an IOException when the mock OutputStream close method is called. We verify easily that the OutputStreamWriter rethrows the exception of the wrapped output stream. To verify actual calls to underlying objects (typical mock object usage), we can use verify(mock_object).method_call; For example:

	@Test
	public void OutputStreamWriter_Closes_OutputStream_on_Close()
		 throws IOException{
		OutputStream mock=mock(OutputStream.class);
		OutputStreamWriter osw=new OutputStreamWriter(mock);
		osw.close();
		verify(mock).close();
	}

This example will verify that OutputStreamWriter propagates the close method call to the wrapped output stream. You can use arguments on methods and matchers such as anyInt() similar to the previous example. Note that you can’t mix literals and matchers, so if you have multiple arguments they all have to be either literals or matchers. use eq(value) matcher to convert a literal into a matcher that compares on value. Mockito comes with lots of matchers already built in, but sometimes you need a bit more flexibility. For example, OutputStreamWriter will buffer output and then send it to the wrapped object when flushed, but we don’t know how big the buffer is upfront. So we can’t use equality matching. However, we can supply our own matcher:

	@Test
	public void OutputStreamWriter_Buffers_And_Forwards_To_OutputStream() 
		throws IOException{		
		OutputStream mock=mock(OutputStream.class);
		OutputStreamWriter osw=new OutputStreamWriter(mock);
		osw.write('a');
		osw.flush();
		// can't do this as we don't know how long the array is going to be
		// verify(mock).write(new byte[]{'a'},0,1);

		BaseMatcher arrayStartingWithA=new BaseMatcher(){
			@Override
			public void describeTo(Description description) {
				// nothing
			}
			// check that first character is A
			@Override
			public boolean matches(Object item) {
				byte[] actual=(byte[]) item;
				return actual[0]=='a';
			}
		};
		// check that first character of the array is A, and that the other two arguments are 0 and 1
		verify(mock).write(argThat(arrayStartingWithA), eq(0),eq(1));	
	}

That’s it – all you need to know to get started. Now go forth and refactor all that easymock ugliness from your projects.

I'm Gojko Adzic, author of Impact Mapping and Specification by Example. My latest book is Fifty Quick Ideas to Improve Your User Stories. To learn about discounts on my books, conferences and workshops, sign up for Impact or follow me on Twitter. Join me at these conferences and workshops:

Specification by Example Workshops

Product Owner Survival Camp

Conference talks and workshops

9 thoughts on “Mockito in six easy examples

  1. Yeah, we have been using Mockito for about a year now and it definitely allows tests to have a cleaner look to them. Too much mocking can leave some bad smells in code but it just seems easier to keep all clean with Mockito. We use RhinoMocks in .NET.

    What I like most about Mockito is the before and after concept of how mocking is to occur. Before the code under test is run is where you declare all of the “when” clauses that tell it how to mock, after the code under test runs is where you declare all of the “verify” clauses that ensure that the correct methods and properties were updated.

    With other mock frameworks there is an awkward relationship between declaring what to mock and also what to expect the code under test to assign to the mock, there is no clean distinction between the two.

    You can also use Mockito to mock without expecting a specific instance, it can be set up to handle just a specific type and much more.

    Example:

    IMyTest someobject = mock(IMyTest.class);

    when(someobject.getValue(isA(Foo.class))).thenReturn(testResult);

    in the above line, Mockito will return testResult whenever the “getValue” routine is called and passed any object of type “Foo” it doesn’t have to be a specific instance.

    The mocking can operate even more specifically than that, but understanding how to handle this is important to know when using Mockito.

  2. Yes, I have used Mockito and it really scores over other mocking framework like JMock…in the sense that, everything is a collaborator and you can choose to setup a stubbing response over it or not and it shields you from other unnecessary stubbings…as the author puts it – “Using expect-run-verify libraries you are often forced to look after irrelevant interactions” and this is a noise (and smell) introduced by testing framework that makes tests brittle…..but with Mockito, you only stub what you need and go on happily completing the functionality.

    Here is how I have used Mockito –> http://www.jroller.com/DhavalDalal/entry/using_stubbedresponsehandler_flushing_out_gwt

  3. If you are testing Mockito, then the examples here are alright.

    But in actual Mockito usage, this is not the proper way of using it. The mock objects are supposed to be collaborators not the actual object under test.

  4. I’m interested in mockito, but there’s one thing I’ve never seen addressed: Can I pass a mockito object as an argument to an ejb 3 stateless bean?

  5. I agree that Mockito is a great Java mocking framework. However, there are frameworks in the Java and .Net world that make mocking even easier, typically by using a more flexible language than Java. One of them is Spock (www.spockframework.org), a Groovy-based testing framework for Java and Groovy apps (disclaimer: I’m the author of Spock). As an exercise, I translated your test code to Spock. I tried to stick as closely to your code as I could, even if that meant writing more code than would be necessary in idiomatic Groovy/Spock. Naturally, more complex tests (like your last example) will see a bigger gain than simple ones. Here is what I came up with:

    void “iterator will return hello world”() {
    given:
    Iterator i = Mock()
    i.next() >>> ["Hello", "World"]

    when:
    String result = i.next() + ” ” + i.next()

    then:
    result == “Hello World”
    }

    void “with arguments”() {
    Comparable c = Mock()
    c.compareTo(“Test”) >> 1
    expect: c.compareTo(“Test”) == 1
    }

    void “with unspecified arguments”() {
    Comparable c = Mock()
    c.compareTo(_ as Int) >> -1
    expect: c.compareTo(5) == -1
    }

    void “OutputStreamWriter rethrows an exception from OutputStream”() {
    OutputStream mock = Mock()
    OutputStreamWriter osw = new OutputStreamWriter(mock)
    mock.close() >> { throw new IOException() }
    when: osw.close()
    then: thrown(IOException)
    }

    void “OutputStreamWriter closes OutputStream on close”() {
    OutputStream mock = Mock()
    OutputStreamWriter osw = new OutputStreamWriter(mock)
    when: osw.close()
    then: 1 * mock.close()
    }

    void “OutputStreamWriter buffers and forwards to OutputStream”() {
    OutputStream mock = Mock()
    OutputStreamWriter osw = new OutputStreamWriter(mock)

    when:
    osw.write(“a”)
    osw.flush()

    then:
    1 * mock.write({ it[0] == “a” }, 0, 1)
    }

  6. Thanks for the post!

    I tried the examples in Netbeans, and the compiler complained when i typed in the last line :

    verify(mock).write(argThat(arrayStartingWithA), eq(0),eq(1));

    It preferred verify(mock).write((byte[])argThat(arrayStartingWithA), eq(0),eq(1));

    have a nice day.

  7. Hi,

    I have inherited method that calls super followed by my own implementation. I want to test this method by calling my own implementation without super call. Is it possible to do this with Mockito ?

    Regards,

    Setya

  8. i am new to mokito

    without implementing the interfaces how can call the methods with interface references

    in mockito,

    we pass the interface class to “mock()” method
    then we call the methods which are present in interface(that methods does not have the body)

    explain the above

    thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>