无法模拟/侦察类java.util.Optional

2022-06-13 00:00:00 mockito java junit junit5

我正在尝试实现此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);

}

相关文章