Mockito, @InjectMocks strange behaviour with final fields

You are using the @InjectMocks for constructor incjection. This will work as long as Mockito finds the field not initalized (null). JUnit is creating a new instance of the test class before each test, so JUnit fans (like me) will never face such problem. TestNg is not creating a new instance of test class. It’s keeping the state between test methods, so when MockitoAnnotations.initMocks(this) is called for the second time, Mockito will find subject field already initialized and will try to use field injection. This on the other turn will work until the field is not final.

Is this is a bug? I believe not – rather a natural consequence of the API design.
Some workaround for you would be to add

this.subject = null;

in some @AfterMethod method.

Leave a Comment