Java mockito

From wikinotes

Documentation

official
mockito docs https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html
mockito homepage https://site.mockito.org/
3rd party
baeldung mock tutorial https://www.baeldung.com/java-spring-mockito-mock-mockbean
vogella mockito tutorial https://www.vogella.com/tutorials/Mockito/article.html

Dependency Manager

maven

JUNIT-5

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>2.27.0</version>
    <scope>test</scope>
</dependency>

Usage

Mockkito.Mock.mock

Mock objects return dummy info whenever methods/attributes are accessed. You can also change the output of specific methods.

import static org.mockito.Mockito.*;

class MyClass { void printhi() {} }
MyClass mock = Mockito.mock(MyClass.class);

when(mock.add(1, 1))
    .thenReturn(4);


Mockito.Spy.spy

Mockito.spy allows you to reuse an object, changing only specific method return values.

import static org.mockito.Mockito.*;

class MyClass {
    Integer add(Integer a, Integer b) { return a + b; }
    Integer sub(Integer a, Integer b) { return a - b; }
}

FileIndexer mock = spy(MyClass.class);
doReturn(4)
    .when(indexer)
    .add(1, 1);


// add's behaviour is changed
mock.add(1, 1);    #> 4

// sub's behaviour is not changed
mock.sub(4, 2);    #> 2

Mocking Methods

import static org.mockito.Mockito.*;

// create mock (classes/interfaces)
LinkedList mockedList = mock(LinkedList.class);
when(mockedList.get(0)).thenReturn("first");

System.out.println(mockedList.get(0));
//> "first"  // 0 was stubbed

System.out.println(mockedList.get(999));
//> null     // 999 was not stubbed