Support @Mock injection in JUnit 5 method parameters
See original GitHub issueJUnit 5 has the ability to “inject” parameters into test methods via an extensible ParameterResolver
interface. The JUnit 5 users guide provides an example that shows how such a ParameterResolver
can supply mock objects as test parameters as follows (shamelessly copied from https://junit.org/junit5/docs/current/user-guide/#writing-tests-dependency-injection):
@ExtendWith(MockitoExtension.class)
class MyMockitoTest {
@BeforeEach
void init(@Mock Person person) {
when(person.getName()).thenReturn("Dilbert");
}
@Test
void simpleTestWithInjectedMock(@Mock Person person) {
assertEquals("Dilbert", person.getName());
}
}
The prototype MockitoExtension
provided in the JUnit 5 samples project shows a simple implementation of the required supportsParameter()
and resolveParameter()
methods. (See: https://github.com/junit-team/junit5-samples/blob/r5.1.0/junit5-mockito-extension/src/main/java/com/example/mockito/MockitoExtension.java)
[ ] Add the ability to inject mock objects into test method parameters to the official MockitoExtension
. References #445
Issue Analytics
- State:
- Created 5 years ago
- Comments:21 (12 by maintainers)
Top GitHub Comments
Okay, to write down the reason I think mock sharing by parameter is not a good idea:
First of all, there is a lot of duplicate code. For every test method, you need to list the mocks, which results in duplicate. Rather, using fields for these mocks removes the duplication.
Secondly, by relying on fields, the compiler will complain when you make a typo (or change a type). With parameters, you rely on the name (String-based) and the type declared. Both are not compiler safe.
Lastly, because you can rely on fields, refactoring is a lot easier, as IDE’s support renaming by field. This is not possible for parameters.
For these 3 reasons, I see field mock sharing superior to parameter mock sharing and am therefore against introducing this logic in the parameter resolution.
Opened #1350 with a proposal implementation.