Peter Penzov
Peter Penzov

Reputation: 1680

Cannot mock/spy class java.util.Optional

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?

Upvotes: 3

Views: 15179

Answers (2)

Ken Chan
Ken Chan

Reputation: 90507

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

}

Upvotes: 7

eamazaj
eamazaj

Reputation: 74

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

Upvotes: 3

Related Questions