2

I'm trying to implement this JUnit code:

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);

}

But I get this error stack:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.util.Optional
Mockito cannot mock/spy because :
 - final class
    at org.data

Do you know how I can fix this issue?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

2 Answers2

7

Remove @Mock on the Optional<BinLists> field.

Optional is a simple class that can be easily created and controlled by you, so you do not need to mock it .Just create an actual instance when you need it which you already do it in 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);

}

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
3

You do not need mock for class Optional (java core class final), you need mock for 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

eamazaj
  • 74
  • 1
  • 3
  • I think you wanted to say `Mockito` instead of `JUnit can't mock the final class`, but that wouldn't be true either. With a recent version of `Mockito` you can [enable final mocking](https://javadoc.io/static/org.mockito/mockito-core/3.1.0/org/mockito/Mockito.html#39). – second Oct 31 '19 at 09:32
  • I've been testing Mockito lately, but I haven't reached that feature, excellent information. I will try it! – eamazaj Oct 31 '19 at 13:57