Skip to content
Advertisement

Mock Property value resides in constructor and add that mock while using @injectBean annotation

I have a class where one attribute is getting value from outer repo.

JavaScript

Now I want to write an unit test for it.

JavaScript

When I run this snippet, it shows a null pointer exception in repository.getValue() May I know how can I mock the value properly to avoid exception?

Advertisement

Answer

The reason that InjectMocks is not working could be because your Repository field is Final.

Kindly see Reference: Mockito injection not working for constructor AND setter mocks together

Resolution:

Example Demo Class:

Notice it is not a Spring Class, Just a simple pojo) just to showcase that we are not autowiring anything here.

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement