Mockito 3


JUnit is great, it provides almost overall functionality to test a module. Junit has a lot of extension points and modules which makes it kind of swiss army knife.

BUt JUnit also has some limitations, just assume we have the below method.

    private AppleRepository appleRepository;

    public Apple saveApple(Apple apple) {
        if (Objects.isNull(apple)) {
            return null;

we need to test the above method using JUNIT, so we create 2 @Test cases.

    @DisplayName("Apple Obj is Null")
    void saveAppleNullTest() {
        AppleService appleService = new AppleService();

The above test case will assert that response is null in case we send the null object. but what if we need to test scenarios where we don't send the null object.

    @DisplayName("Apple Obj is not Null")
    void saveAppleNotNullTest() {
        AppleService appleService = new AppleService();
        Apple apple = new Apple("macintosh");

now in the above test case, because the apple object is not null hence it will proceed and actually save apple object in the database.

Now testing these types of methods has a collateral effect, we can't test them for a positive scenario because it will change the state of the actual database, which is not required.
if only we could somehow tell code to not save data in Database. Mockito comes to rescue.

Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with a clean & simple API. Mockito doesn’t give you hangover because the tests are very readable and they produce clean verification errors.

Mockito allows convenient methods for the creation of substitutes of real objects for testing purposes or in simple words it tells the classes to provide dummy or in Mockito terms, stub response, ie, behave like you are working but don't work.

JUnit works on notation of "expected" and "actual" whether Mockito understand stubbing and verifications.


Mockito primarily focuses on mocking, stubbing, and faking objects, but it has no way to run test cases on its own, for that it's dependent on JUnit only, we will be using the latest Mockito 3 with JUnit 5 Jupiter.

if pure Mockito is required without Junit then use

dependencies {
    testCompile 'org.mockito:mockito-core:3.4.4'

but if Mockito is used with JUnit 5 then Mockito provides another artifact mockito-junit-jupiter, it provides Junit Extensions to register Mockito.

dependencies {
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'

please don't use mockito-all dependency, it has been discontinued.

Legacy builds with manual dependency management can use 1.* “mockito-all” distribution. It can be downloaded from Mockito’s Bintray repository or Bintray’s jcenter. “mockito-all” distribution has been discontinued in Mockito 2.*

follow us on