Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return class from method in mocked method. Mockito

I have class TaskType. It has method

public Class<? extends TaskParameters> getTypeParameters() {
    return typeParameters;
}

next i want to mock this class and mock this method:

    final TaskType TEST_PARAMETERS = Mockito.mock(TaskType.class);
    when(TEST_PARAMETERS.getTypeParameters()).thenReturn(ScheduledParameters.class);
    Mockito.doReturn(4).when(TEST_PARAMETERS).ordinal();

but i got problem:

error: no suitable method found for thenReturn(java.lang.Class<com.ucp.shard.bulkops.service.executor.ScheduleExecutorTest.ScheduledParameters>)
        when(TEST_PARAMETERS.getTypeParameters()).thenReturn(ScheduledParameters.class);

Help, how can i mock this method?

like image 501
kepich Avatar asked Sep 14 '26 09:09

kepich


1 Answers

Your question is missing a lot of information, it would be nice if you could update it. For example, you could share the code for TaskType.

First of all, it seems that TaskType is an enum as you are trying to call ordinal(), right? If it's the case, you need to remember that enums are final and cannot be mocked by Mockito by default (please read here for more information). If it's not an enum you can ignore it. :)

Regarding the problem mocking getTypeParameters(), you cannot do it directly due to type erasure (more information here). However, you can solve it using Mockito Answer:

final TaskType TEST_PARAMETERS = Mockito.mock(TaskType.class);
final Answer<Class<ScheduledParameters>> answer = invocation -> ScheduledParameters.class;
when(TEST_PARAMETERS.getTypeParameters())
    .thenAnswer(answer);
Mockito.doReturn(4).when(TEST_PARAMETERS).ordinal();
like image 136
Igor Brito Alves Avatar answered Sep 15 '26 22:09

Igor Brito Alves