Mockito 2 now available

Home » Blog » Software » Enterprise Software » Mockito 2 now available

Last week version 2.1.0 of the Mockito testing framework for Java has been released. For more information on this latest iteration check out this page.

As the name suggests, Mockito allows you to mock object behaviour during unit tests. When writing unit tests you only want to test a particular unit’s behaviour (hence the name). Depending on the programming language used such a unit might be a function, a procedure or – most commonly in today’s object-oriented programming environments – a class. Given how tightly coupled such a unit is to other components it might not be entirely possible to test its behaviour in isolation.

The most common cases of such tight coupling are dependencies on external systems such as databases or email servers. Another issue that occurs particularly often with more heavy-weight enterprise frameworks for the Java platform such as Spring is that those frameworks often require a complex object hierarchy that’s typically created during an application’s bootstrap phase. Both due to performance considerations (unit tests should run very fast after all) and in order to focus on the behaviour of the tested unit (and not some ancillary tooling that doesn’t add to the information provided by the unit test) manually building these object hierarchies during unit tests should be avoided.

Now while to some extent it’s true that both tight coupling with external components and the dependency on a complex object hierarchy are code smells neither can be avoided completely in most cases. It’s in these situations where a mocking framework comes in handy. Mockito is the by far most popular one for the Java platform and the de-facto standard for mocking object behaviour. In a nutshell, it works like this (example taken from the Mockito website):


...
List mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("first");

// the following prints "first"
System.out.println(mockedList.get(0));

This way you can simulate an objects internal behaviour without actually having to satisfy its dependencies such as a database server being available or having been initialised with another object. That means you can delegate simulating behaviour extraneous to your test to Mockito while focussing on the unit test at hand.

Leave a Comment

By continuing to use the site you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or if you click "Accept" below then you are consenting to this.

Close