本文介紹了無法模擬/偵察類java.util.Optional的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試實現此JUnit代碼:
private BinlistsService binlistsService = Mockito.mock(BinlistsService.class);
@Mock
Optional<BinLists> binList = null;
@BeforeEach
public void beforeEachTest() throws IOException {
BinLists binLists = new BinLists();
binLists.setId(1);
....
binList = Optional.of(binLists);
}
@Test
public void testBinCountryCheckFilterImpl() {
when(binlistsService.findByName(anyString())).thenReturn(binList);
}
但我收到以下錯誤堆棧:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.util.Optional
Mockito cannot mock/spy because :
- final class
at org.data
您知道我如何解決此問題嗎?
推薦答案
刪除Optional<BinLists>
字段上的@Mock
。
Optional
是一個簡單的類,您可以很容易地創建和控制它,所以您不需要模擬它。只需在需要的時候創建一個實際的實例,beforeEachTest()
:
private BinlistsService binlistsService = Mockito.mock(BinlistsService.class);
Optional<BinLists> binList = null;
@BeforeEach
public void beforeEachTest() throws IOException {
BinLists binLists = new BinLists();
binLists.setId(1);
....
binList = Optional.of(binLists);
}
@Test
public void testBinCountryCheckFilterImpl() {
when(binlistsService.findByName(anyString())).thenReturn(binList);
}
這篇關于無法模擬/偵察類java.util.Optional的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,