0

I Have the following structure of a class:

public class MyClass <T extends InterfaceA & InterfaceB> {
private final T someOtherClass;

public MyClass(T someOtherClass){
 this.someOtherClass = someOtherClass;
 }
}

Now I want to test this class and for that I need to mock the someOtherClass. Here is what I have for my tests:

@ExtendWith(MockitoExtension.class)
public class MyeTest {
//NewClass implements both interfaces: InterfaceA and InterfaceB
@Mock
private NewClass newClass;

@InjectMocks
private MyClass<NewClass> myClass;

@Test
void someTest() {
//...
}

Error Message that I get: org.mockito.exceptions.misusing.InjectMocksException: Cannot instantiate @InjectMocks field named 'myClass' of type MyClass. You haven't provided the instance at field declaration so I tried to construct the instance. However the constructor or the initialization block threw an exception : null

Within test I tried to add a new empty interface that extends both InterfaceA and InterfaceB, and use it instead of a NewClass that implements both interfaces, like that:

@Mock
private InterfaceAandB someName;
@InjectMocks
private MyClass<InterfaceAandB> myClass;

But I still get the same error message.

Shad
  • 1
  • 1
  • 1
    That's odd; I don't see a way how your class' constructor could throw an NPE – knittl Jan 11 '23 at 19:03
  • Also, I copied the code from your question and it compiles and runs just fine (JUnit 5.8.2, Mockito 4.5.1). No exceptions, all fields are initialized and the mock is properly injected. Perhaps one of the reasons outlined in [Why is my class not calling my mocked methods in unit test?](https://stackoverflow.com/q/74027324/112968) – knittl Jan 11 '23 at 19:09

0 Answers0