Mockito

  • When the MockitoJUnitRunner executes a test, in the before phase, Mockito creates mocks and spies instances for all @Mock or @Spy fields, and injects them into the @InjectMocks field.
  • The order of DI attempts is constructor, setter, fields.
  • final or static fields are not supported, but private are.
  • Uses refelction internally.
// v1: POJO, v2: @Named("example"), v3: Component("example")
public class Example {
    // v2: @Inject, v3: @Autowired
    private Delegate delegate;

    public Example(Delegate delegate) {
        this.delegate = delegate;
    }

    public void doSomething() {
        delegate.execute();
    }
}

// testing any of these 3 versions:
@RunWith(MockitoJUnitRunner.class)
public void ExampleTest {
    @Mock
    Delegate delegate;

    @InjectMocks
    Example example;

    @Test
    public void doSometingTest() {
        example.doSomething();
        verify(delegate).execute();
    }
}