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):

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.