mockito5.4.0单元测试(4) --主动throw异常,模拟异常处理

发布时间 2023-06-19 16:18:16作者: 梦幻朵颜
import static org.mockito.Mockito.*;    // 引入类
 
 
LinkedList mockedList = mock(LinkedList.class);     // 获得mock对象
 
//stubbing
when(mockedList.get(0)).thenReturn("first");          // 如果获取0索引,则返回:first 
when(mockedList.get(1)).thenThrow(new RuntimeException());  // 如果获取1索引,则throw异常
 
//following prints "first"
System.out.println(mockedList.get(0));     // 正常获得0: first
 
//following throws runtime exception
System.out.println(mockedList.get(1));    // 代码抛出异常,执行被终止
 
//following prints "null" because get(999) was not stubbed    
System.out.println(mockedList.get(999));       // 如果get(1) 那一行代码被注释掉,则这里执行得到的是个Null
 
verify(mockedList).get(0);       // 校验曾经交互get过0这个索引对象,如果get(1) 那一行被注释掉,则代码会执行到这里,并且会pass
verify(mockedList).get(10);      // 校验曾经交互get过10这个索引对象,如果get(1) 那一行被注释掉,则代码会执行到这里,但是会fail失败,因为上面的交互行为中从来没有被get过10索引