通过 mockito 创建一个模拟列表
2022-09-01 04:28:25
我想创建一个模拟列表来测试下面的代码:
for (String history : list) {
//code here
}
这是我的实现:
public static List<String> createList(List<String> mockedList) {
List<String> list = mock(List.class);
Iterator<String> iterHistory = mock(Iterator.class);
OngoingStubbing<Boolean> osBoolean = when(iterHistory.hasNext());
OngoingStubbing<String> osHistory = when(iterHistory.next());
for (String history : mockedList) {
osBoolean = osBoolean.thenReturn(true);
osHistory = osHistory.thenReturn(history);
}
osBoolean = osBoolean.thenReturn(false);
when(list.iterator()).thenReturn(iterHistory);
return list;
}
但是当测试运行时,它会在行中引发异常:
OngoingStubbing<DyActionHistory> osHistory = when(iterHistory.next());
详细信息:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:495)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
我该如何修复它?谢谢