Mockito, @InjectMocks strange behaviour with final fields

后端 未结 1 908
旧时难觅i
旧时难觅i 2020-12-11 02:08

I am seeing behaviour that I believe is a bug. @InjectMocks does not seem to create a new test subject before every test method. Where as @Mock does. In the following exampl

相关标签:
1条回答
  • 2020-12-11 02:57

    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.

    0 讨论(0)
提交回复
热议问题