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.
java testng mockito
user1945457
source share