为什么在没有定义 subbing 时 mock 不会 return null

how come mock doesn't return null when no subbing defined

我看了 mockito 官方文档

我不明白:

1. Let's verify some behaviour!

01
//Let's import Mockito statically so that the code looks clearer
02
import static org.mockito.Mockito.*;
03

04
//mock creation
05
List mockedList = mock(List.class);
06

07
//using mock object
08
mockedList.add("one");
09
mockedList.clear();
10


11
//verification
12
verify(mockedList).add("one");
13
verify(mockedList).clear();
Once created, mock will remember all interactions. Then you can selectively verify whatever interaction you are interested in.

2. How about some stubbing?

01
//You can mock concrete classes, not only interfaces
02
LinkedList mockedList = mock(LinkedList.class);
03

04
//stubbing
05
when(mockedList.get(0)).thenReturn("first");
06
when(mockedList.get(1)).thenThrow(new RuntimeException());
07

08
//following prints "first"
09
System.out.println(mockedList.get(0));
10

11
//following throws runtime exception
12
System.out.println(mockedList.get(1));
13

14
//following prints "null" because get(999) was not stubbed
15
System.out.println(mockedList.get(999));

怎么会

08 mockedList.add("one");

不会 return 为 null,因为没有定义存根。

如此处所示:

14 //following prints "null" because get(999) was not stubbed 15 System.out.println(mockedList.get(999));

08 mockedList.add("one");

是加而不是像 15