Page cover image

Mockito

About

Mockito is a mocking framework for unit tests in Java. It won't leave you with a hangover, thanks to its highly readable tests and clean verification errors.

It doesn’t use expect-run-verify pattern. With Mockito, you ask questions about interactions after execution, streamlining your testing process.

Features

Mocking

The Mockito.mock(class) method is a powerful feature enabling the creation of a mock object for a specified class or an interface, essentially generating a proxy. This mock object serves various purposes, such as stubbing return values for its methods and verifying whether these methods were called during the test execution. Additionally, the mocked instance can be seamlessly integrated into your test using the @Mock annotation, especially when paired with @InjectMocks and @ExtendWith(MockitoExtension.class)— simplifying the process of injecting mocks into the target object. For scenarios where you prefer to mock or spy without explicitly specifying the class, the Mockito.mock() method comes in handy, allowing for dynamic and flexible mocking or spying without being tied to a particular class in advance.

Example:

@ExtendWith(MockitoExtension.class)
class MockingExampleTest {
    //First
    private final UserService mocked_service1 = mock(UserService.class);
    
    //Second
    @Mock
    private UserService mocked_service2;

    @Test                 //Third
    void mocking_example(@Mock final UserService mocked_service3) {
        //using mock object
        mocked_service3.getServiceName();

        //verification
        verify(mocked_service3).getServiceName();
    }
}

Last updated