How can I use Mockito JUnit 5 for dependency injection?
In JUnit 4, I can simply use the @RunWith(MockitoJUnitRunner.class)
annotation to enable Mockito. However, in JUnit 5, there is no equivalent @RunWith
annotation.
How can I achieve dependency injection with Mockito in JUnit 5?
Hey
To resolve your query, you can use @ExtendWith(MockitoExtension.class)
; this helped me resolve the issue I was facing the same as yours.
In JUnit 5, the @ExtendWith
annotation is used to integrate Mockito into tests. This is the preferred way to enable Mockito extensions for dependency injection in JUnit 5.
@ExtendWith(MockitoExtension.class)
public class MyTest {
@Mock
private MyService myService;
@Test
public void testMyService() {
when(myService.doSomething()).thenReturn("result");
assertEquals("result", myService.doSomething());
}
}
Hope I was able to help you
If you prefer manual control over initialization, you can use MockitoAnnotations.openMocks(this)
in the setup method, which is an alternative to @ExtendWith
and initializes mock objects for JUnit 5.
public class MyTest {
@Mock
private MyService myService;
@BeforeEach
public void initMocks() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testMyService() {
when(myService.doSomething()).thenReturn("result");
assertEquals("result", myService.doSomething());
}
}
Mockito JUnit 5 allows the use of @Mock
for mock objects and @InjectMocks
for the class under test. These annotations work together to automatically inject the mocks into the class being tested.
@ExtendWith(MockitoExtension.class)
public class MyTest {
@Mock
private MyService myService;
@InjectMocks
private MyController myController;
@Test
public void testController() {
when(myService.doSomething()).thenReturn("result");
assertEquals("result", myController.getServiceResult());
}
}