Mockito 1.8 - New Useful Features

DZone 's Guide to

Mockito 1.8 - New Useful Features

· Java Zone ·
Free Resource

Mockito expands its impressive feature set with release 1.8.I was once a happy EasyMock user. If asked, I think I would have even questioned the need for a new mocking framework – EasyMock did it all, didn’t it?

But after using Mockito for a short while I was impressed by its efficiency and ease of use. The key features for me were its simple and intuitive API and the way any Mock object will return sensible defaults for all of its methods – allowing you to concentrate on the behaviour of the methods you care about. The framework continues to improve incrementally with each release. This post gives a quick view of two of the most useful new features in Mockito 1.8

BDD-Style Language Supported Natively

BDD (Behaviour Driven Development) is rapidly becoming mainstream. Standard BDD conventions recommend the use of given-when-then comments in your tests. This allows improved readability by giving clear delineation between test setup, execution and assertions. Mockito’s choice of method names previously were in conflict with these BDD conventions. Version 1.8 allows you to stick with the BDD conventions while also remaining backward compatible will older Mockito tests.

  import static org.mockito.BDDMockito.*;

Seller seller = mock(Seller.class);
Shop shop = new Shop(seller);

public void shouldBuyBread() throws Exception {

given(seller.askForBread()).willReturn(new Bread());

Goods goods = shop.buyBread();

assertThat(goods, containBread());

Capturing arguments

Mockito has always supported a wide range of matchers to allow verification that mocked methods are invoked with the expected arguments. However sometimes (especially when dealing with legacy code) this can limit the checks you can do without the overhead of writing a custom matcher. 

Version 1.8 introduces new functionality to allow you to capture and store the arguments passed the mocked methods. Standard jUnit assertions can then be applied to the captured arguments. Over reliance on capturing arguments would be a code smell in my opinion as most well abstracted code should not need to do this. However for testing legacy code and interactions with outside systems ArgumentCaptors can be very useful.

   ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);  
assertEquals("John", argument.getValue().getName())

More Info…

Downloads and more information can be found at mockito.org. For maven users – simply add the following dependency to your pom:


Taken from my blog at http://decodify.blogspot.com/2009/10/mockito-18-new-useful-features.html


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}