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

Cannot mock/spy class java.util.Optional(无法模拟/侦察类java.util.Optional)

本文介绍了无法模拟/侦察类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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法模拟/侦察类java.util.Optional

基础教程推荐