How can I use injection with Mockito and JUnit 5?
In JUnit4 I can just use the @RunWith(MockitoJUnitRunner.class)
Annotation. In JUnit5 is no @RunWith
Annotation?
Mockito provides an implementation for JUnit5 extensions in the library — mockito-junit-jupiter.
MockitoJUnitRunner. Mock objects can be created using Mockito JUnit Runner ( MockitoJUnitRunner ). This runner is compatible with JUnit 4.4 and higher, this runner adds the following behavior: Initializes mocks annotated with @Mock , so that explicit usage of MockitoAnnotations#initMocks(Object) is not necessary.
To include powermock in our application, add the powermock-api-mockito2 and powermock-module-junit4 dependencies. Note that there is no official extension for JUnit 5. If you plan to use its reflection module, for example invoking the private methods, then we need to import powermock-reflect module as well.
There are different ways to use Mockito - I'll go through them one by one.
Creating mocks manually with Mockito::mock
works regardless of the JUnit version (or test framework for that matter).
Using the @Mock-annotation and the corresponding call to MockitoAnnotations::initMocks
to create mocks works regardless of the JUnit version (or test framework for that matter but Java 9 could interfere here, depending on whether the test code ends up in a module or not).
JUnit 5 has a powerful extension model and Mockito recently published one under the group / artifact ID org.mockito : mockito-junit-jupiter.
You can apply the extension by adding @ExtendWith(MockitoExtension.class)
to the test class and annotating mocked fields with @Mock
. From MockitoExtension
's JavaDoc:
@ExtendWith(MockitoExtension.class)
public class ExampleTest {
@Mock
private List list;
@Test
public void shouldDoSomething() {
list.add(100);
}
}
The MockitoExtension documentation describes other ways to instantiate mocks, for example with constructor injection (if you rpefer final fields in test classes).
JUnit 4 rules and runners don't work in JUnit 5, so the MockitoRule
and the Mockito runner can not be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With