【问题标题】:how come mock doesn't return null when no subbing defined当没有定义底片时,mock 怎么不返回 null
【发布时间】:2026-02-11 09:40:02
【问题描述】:

我看了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");

不返回 null,因为没有定义存根。

如下所示:

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

【问题讨论】:

    标签: java unit-testing mocking mockito


    【解决方案1】:

    08 mockedList.add("one");

    加起来不像 15

    【讨论】:

    • add() 也没有定义。这不是错误?
    • 所以我们不必存根任何返回“void”而只返回非 void 方法的东西?
    • 上线5 List mockedList = mock(List.class);为 Collection List 创建了一个 Mock。 List 有 add 和 get 方法。 get(999) 返回 null,因为没有值 999 被添加到列表中。
    • verify(mockedobject).somemethod 用于验证使用列出的参数在模拟对象上调用了某个方法,因此它就像一个 assertThat(mockedobject.somemethod().wasCalled() ) - 如果这甚至是可能的。-验证确认您尝试将(“一个”)添加到您的模拟对象,但与所述模拟的内容无关。