I want to mock a lazy injection with deep stubs using:
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
Instance<MyClass> myClassInstance;
But myClassInstance.get().myMethod()
results in a NullPointerException because myClassInstance.get()
returns null
instead of a mock.
Is this an unsupported feature or am I doing something wrong?
I'm using junit-jupiter 5.9.0 and mockito-junit-jupiter 4.6.1.
CodePudding user response:
This is a result of erasure of generic types. Mockito does not have access to the actual type returned by the get()
method and in result null
is returned. See ReturnsDeepStubs class code in the Mockito GitHub repository for more details.
To work around that you should mock returning the stub from the get()
method by hand in your test code or in a test setup method (@BeforeEach
).