Do Mock objects get reset for each test?

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class sandbox {

    @Mock
    private MyClass myMock;

    @Before
    public void setup() {
        when(myMock.myMethod()).thenReturn("hello");
    }

    @Test
    public void test1() {
        myMock.myMethod();
        verify(myMock, times(1)).myMethod();
    }

    @Test
    public void test2() {
        myMock.myMethod();
        verify(myMock, times(1)).myMethod();
    }

}

This passes. If the state persisted then the second test would fail. If you debug it you would see that you get a new instance of the mocked object for each test.


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.