mockito Getting started with mockito Create objects mocked by Mockito


Example

There are two ways to create object mocked by Mockito:

  • via annotation
  • via mock function

Via annotation:

With a JUnit test runner:

@RunWith(MockitoJUnitRunner.class)
public class FooTest {
    @Mock
    private Bar barMock;

    // ...
}

You can also use Mockito's JUnit @Rule, which provides the same functionality as the MockitoJUnitRunner, but doesn't need a @RunWith test runner:

public class FooTest {
    @Rule
    public MockitoRule mockito = MockitoJUnit.rule();        

    @Mock
    private Bar barMock;

    // ...
}

If you can't use @RunWith or the @Rule annotation you can also init mocks "per hand":

public class FooTest {
    @Mock
    private Bar barMock;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    // ...
}

Via mock function:

public class FooTest {
    private Bar barMock = Mockito.mock(Bar.class);

    // ...
}

Because of type erasure, you cannot mock a generic class as above. You must mock the base class and explicitly cast to the right generic type:

public class FooTest {
    private Bar<String> genericBarMock = (Bar<String>) Mockito.mock(Bar.class);

    // ...
}