Category Archives: blog #6

Detailed and basic usage of Mockito

 Mockito is a Mock framework for Java single-testing, but it can also be used with other single-testing frameworks in addition to JUnit. Mockito changes the behavior of a class or object, allowing us to focus more on testing the code logic without the effort of constructing the data.

The basic concept

Mocks can be of two types, Class and Partial,so Mockito is called spy. The behavior of changing methods on mock objects is called Stub.

A Mock process is called a Mock Session, and it records all the Stubbing. It consists of three steps:

+———-+ +——+ +——–+ | Mock/Spy | ===> | Stub | ===> | Verify | +———-+ +——+ +——–+

Class Mock

A Class Mock changes the behavior of a Class so that the object it mocks completely loses its original behavior.

Method returns default values (null, false, 0, etc.) if it is not pegged.

The most basic usage is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
import static org.mockito.Mockito.*;

// use List.class to creat a mock subject --- mockedList

List mockedList = mock(List.class);

//operation of mockedList

mockedList.add("one");
mockedList.clear();

//validation

verify(mockedList).add("one");
verify(mockedList).clear();

Partial Mock(spy)

If we only want to change the behavior of an instance, we need to use spy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
List list = new LinkedList();
List spy = spy(list);

// optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

// using the spy calls *real* methods
spy.add("one");
spy.add("two");

// prints "one" - the first element of a list
System.out.println(spy.get(0));

// size() method was stubbed - 100 is printed
System.out.println(spy.size());

// optionally, you can verify
verify(spy).add("one");
verify(spy).add("two");

As you can see from the code, the main difference between a Spy and a MockSettings is that the MockSettings for a Spy needs to be passed in a SpiedInstance.

The default Answer to a spy is CALLS_REAL_METHODS, which means that if a method is not stub, it performs its real behavior.

The default Answer to a mock is RETURNS_DEFAULTS. Methods that are not stub return a default value.

source:

https://www.vogella.com/tutorials/Mockito/article.html

https://howtodoinjava.com/mockito/junit-mockito-example/

From the blog haorusong by and used with permission of the author. All other rights reserved by the author.