Mockito, @InjectMocks weird behavior with finite fields

I see behavior that I think is a mistake. @InjectMocks does not seem to create a new test object before each testing method. Where does @Mock work. In the following example, if Subject.section is final, one @Test fails. If its not final, both will pass. My current workaround is to use @BeforeClass, but this is not ideal.

Subject.java:

package inject_mocks_test; public class Subject { private final Section section; public Subject(Section section) { this.section = section; } public Section getSection() { return section; } } 

Section.java:

 package inject_mocks_test; public class Section {} 

SubjectTest.java

 package inject_mocks_test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class SubjectTest { @Mock Section section; @InjectMocks Subject subject; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); } @Test public void test1() { assertEquals(section, subject.getSection()); } @Test public void test2() { assertEquals(section, subject.getSection()); } } 

Greetings.

+7
java testng mockito
source share
1 answer

You are using the @InjectMocks construct for the constructor . This will work until Mockito detects that the field is not initialized (null). JUnit creates a new instance of the test class before each test, so JUnit fans (like me) will never encounter such a problem. TestNg does not create a new instance of the test class. It maintains state between test methods, so when MockitoAnnotations.initMocks(this) is called a second time, Mockito will find the object field already initialized and try to use the field injection. This, on the other hand, will work until the field is final.

This is mistake? I believe not - rather a natural consequence of the design of the API. Some workaround for you is to add

 this.subject = null; 

in some @AfterMethod method.

+17
source share

All Articles