'Mockito "cannot select from parameterized type" issue

I'm trying to mock for testing purpose:

ClassA classA = Mockito.mock(ClassA.class);

Mockito.when(classA.void(Mockito.any(ClassB<String, ClassC>.class), Mockito.any(ClassD.class))).thenReturn("passed");

but I have info on "ClassB<String, ClassC>": cannot select from parameterized type.

ClassA void: ClassA.void(@NotNull ClassB<String, ClassC> classB, ClassD classD){...}

mockito-core-4.0.0, springboot, maven

Any idea how to solve it?



Solution 1:[1]

Okay,Here is what you need to do in Order to Solve your problem.

First replace this line:ClassA classA = Mockito.mock(ClassA.class); With

@MockBean
private Class classA;

As a class level variable. After that you need to change your following piece of code:

ClassB<String, ClassC>.class

To

ClassB<Mockito.anyString(), Mockito.any(ClassC.class)>.class

Hopefully this will solve your problem. Please accept if it works.

Solution 2:[2]

Because this is a "void" that returns nothing, it is impossible for it to return a String value. Solution is: Mockito.doThrow(new Exception("Error occurred")).when(classA).void(Mockito.any(ClassB.class), Mockito.any(ClassD.class)); and then classA.void(Mockito.any(ClassB.class), Mockito.any(ClassD.class)); ..... 'voidName' is a void method and it cannot be stubbed with a return value! Voids are usually stubbed with Throwables: doThrow(exception).when(mock).someVoidMethod(); If you need to set the void method to do nothing you can use: doNothing().when(mock).someVoidMethod();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jayesh Choudhary
Solution 2 Bartek