Issue
I'm using the Mockito framework to create Mock objects in my JUnit tests. Each mock knows what methods have been called on it, so during my tests I can write
verify(myMock, atLeastOnce()).myMethod();
I am wondering if this internal mock knowledge of what it has called will persist across my tests? If it does persist, then I could be getting false positives when using the same verify
method in two tests.
A code example
@RunWith(MockitoJUnitRunner.class)
public class EmrActivitiesImplTest {
@Mock private MyClass myMock;
@Before
public void setup() {
when(myMock.myMethod()).thenReturn("hello");
}
@Test
public void test1() {
// ..some logic
verify(myMock, atLeastOnce()).myMethod();
}
@Test
public void test2() {
// ..some other logic
verify(myMock, atLeastOnce()).myMethod();
}
}
Mock state is persisted - test2 will pass regardless, since test1's verify method passed
Mock state is reset - test2 will fail if myMock.myMethod() isn't called
Solution
JUnit creates a new instance of test class each time it runs a new test method and runs @Before
method each time it creates a new test class. You can easily test it:
@Before
public void setup() {
System.out.println("setup");
when(myMock.myMethod()).thenReturn("hello");
}
And MockitoJUnitRunner
will create a new MyMock
mock instance for every test method.
Answered By - Evgeniy Dorofeev
Answer Checked By - Candace Johnson (JavaFixing Volunteer)