Java Testing Frmeworks
created: 18 January 2021
revision: 1
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
orstatic
fields are not supported, butprivate
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();
}
}