Mockito 3 Naming Mocks

Mockito provides a clean message and stack trace in case of assertion failure, but as application grows, with lots of mock and stubs some times it can create confusion about the invocation of mocks. To solve this solution Mockito allows to name mock instances.

Naming a mock instance is very helpful at the time of debugging and the same name is used in all verification error stack trace.

Naming mocks can be helpful for debugging - the name is used in all verification errors.

Mock instance created with @Mock annotation if not explicetly provided then will by default name the mock instance with the variable name.

Static mock method provides 2 ways to name a mock.

AppleService appleService = mock(AppleService.class, withSettings().name("appleMock"));

is equal to

AppleService appleService = mock(AppleService.class, "appleMock");
package com.example.mokito3.sujan;

public class AppleService {
    public String saveApple(String apple) {
        String appleString = "i love " + apple + " apple";
        return appleString;
    }
}
package com.example.mokito3.sujan;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

@ExtendWith(MockitoExtension.class)
public class AppleServiceTest {
    @Mock(name = "appleMock")
    private AppleService appleService;

    @Test
    void saveAppleWithStaticMockTest() {
        AppleService appleService = mock(AppleService.class, "appleMock");
        System.out.println("mock name is " + Mockito.mockingDetails(appleService).getMockCreationSettings().getMockName());
        String apple = appleService.saveApple("Macintosh");
        verify(appleService).saveApple("Macintosh");
        assertEquals("i love Macintosh apple", apple);
    }

    @Test
    void saveAppleWithAnnotationMockTest() {
        System.out.println("mock name is " + Mockito.mockingDetails(appleService).getMockCreationSettings().getMockName());
        String apple = appleService.saveApple("Macintosh");
        verify(appleService).saveApple("Macintosh");
        assertEquals("i love Macintosh apple", apple);
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories { jcenter() }
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
    testCompile 'org.mockito:mockito-junit-jupiter:3.4.4'
}
test {
    useJUnitPlatform()
}

 

follow us on