eriksmith200
eriksmith200

Reputation: 2179

Mocking Instance<T> with deep stubs

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.

Upvotes: 0

Views: 288

Answers (1)

Jonasz
Jonasz

Reputation: 1802

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

Upvotes: 1

Related Questions