簡體   English   中英

無法模擬/窺探 class java.util.Optional

[英]Cannot mock/spy class 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的是一個簡單的 class ,您可以輕松地創建和控制它,因此您不需要模擬它。只需在需要時創建一個實際實例,您已經在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);

}

您不需要模擬class Optional (java 核心 class final ),您需要模擬class BinLists

    @Mock
    BinLists binList = null;

JUnit can`t mock the final class, but if you need this unusual technique of mocking can use PowerMock https://github.com/powermock/powermock

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM