問題描述
我想創(chuàng)建一個模擬列表來測試以下代碼:
I want to create a mocked list to test below code:
for (String history : list) {
//code here
}
這是我的實現(xiàn):
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;
}
但是當測試運行時,它會在以下行拋出異常:
But when the test run it throw exception at line:
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!
我該如何解決?謝謝
推薦答案
好吧,這是一件壞事.不要模擬列表;相反,模擬列表中的各個對象.請參閱 Mockito:模擬將在 for 循環(huán)中循環(huán) 以了解如何執(zhí)行此操作.
OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.
另外,您為什么要使用 PowerMock?你似乎沒有做任何需要 PowerMock 的事情.
Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.
但問題的真正原因是您在完成存根之前在兩個不同的對象上使用了 when
.當您調(diào)用 when
并提供您嘗試存根的方法調(diào)用時,您在 Mockito 或 PowerMock 中所做的下一件事就是指定調(diào)用該方法時會發(fā)生什么 - 也就是說,執(zhí)行 thenReturn
部分.每次對 when
的調(diào)用必須跟一個且只有一個對 thenReturn
的調(diào)用,然后再對 when
進行任何調(diào)用.您對 when
進行了兩次調(diào)用而沒有調(diào)用 thenReturn
- 這是您的錯誤.
But the real cause of your problem is that you are using when
on two different objects, before you complete the stubbing. When you call when
, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn
part. Each call to when
must be followed by one and only one call to thenReturn
, before you do any more calls to when
. You made two calls to when
without calling thenReturn
- that's your error.
這篇關于通過 mockito 創(chuàng)建一個模擬列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!