Class MockitoJUnitRunner

java.lang.Object
org.junit.runner.Runner
org.mockito.junit.MockitoJUnitRunner
All Implemented Interfaces:
Describable, Filterable
Direct Known Subclasses:
MockitoJUnitRunner.Silent, MockitoJUnitRunner.Strict, MockitoJUnitRunner.StrictStubs

public class MockitoJUnitRunner extends Runner implements Filterable
Mockito JUnit Runner keeps tests clean and improves debugging experience. Make sure to try out MockitoJUnitRunner.StrictStubs which automatically detects stubbing argument mismatches and is planned to be the default in Mockito v3. Runner is compatible with JUnit 4.4 and higher and adds following behavior:
  • (new since Mockito 2.1.0) Detects unused stubs in the test code. See UnnecessaryStubbingException. Similar to JUnit rules, the runner also reports stubbing argument mismatches as console warnings (see MockitoHint). To opt-out from this feature, use @RunWith(MockitoJUnitRunner.Silent.class)
  • Initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.openMocks(Object) is not necessary. Mocks are initialized before each test method.
  • Validates framework usage after each test method. See javadoc for Mockito.validateMockitoUsage().
  • It is highly recommended to use MockitoJUnitRunner.StrictStubs variant of the runner. It drives cleaner tests and improves debugging experience. The only reason this feature is not turned on by default is because it would have been an incompatible change and Mockito strictly follows semantic versioning.
Runner is completely optional - there are other ways you can get @Mock working, for example by writing a base class. Explicitly validating framework usage is also optional because it is triggered automatically by Mockito every time you use the framework. See javadoc for Mockito.validateMockitoUsage().

Read more about @Mock annotation in javadoc for MockitoAnnotations


 @RunWith(MockitoJUnitRunner.StrictStubs.class)
 public class ExampleTest {

     @Mock
     private List list;

     @Test
     public void shouldDoSomething() {
         list.add(100);
     }
 }
 
If you would like to take advantage of Mockito JUnit runner features, but you cannot use the runner there is a solution! MockitoSession API is intended to offer cleaner tests and improved debuggability to users that cannot use Mockito's built-in JUnit support (runner or the rule).