What is a Junit Extension
The purpose of Junit 5 extensions is to extend the behavior of test classes or methods
source
Read on Junit 5 Extension Model & @ExtendWith annotation :here
SpringExtension
SpringExtension integrates the Spring TestContext Framework into JUnit
5’s Jupiter programming model.
public class SpringExtension
extends Object
implements BeforeAllCallback, AfterAllCallback, TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback, ParameterResolver{..}
MockitoExtension
This extension is the JUnit Jupiter equivalent of our JUnit4
MockitoJUnitRunner
public class MockitoExtension
extends java.lang.Object
implements BeforeEachCallback, AfterEachCallback, ParameterResolver{..}
As it can be seen , SpringExtension implements a lot more extensions than MockitoExtension.
Also @SpringBootTest is meta annotated with @ExtendWith(SpringExtension.class) and which means every time your tests are extended with SpringExtension.
@MockBean is a Spring test framework annotation and used along with @ExtendWith(SpringExtension.class)
To observe the difference try the following
ExtendWith only MockitoExtension
@ExtendWith(MockitoExtension.class)
class TestServiceTest {
@MockBean
TestService service;
@Test
void test() {
assertNotNull(service); // Test will fail
}
}
ExtendWith only SpringExtension
@ExtendWith(SpringExtension.class)
class TestServiceTest {
@MockBean
TestService service;
@Test
void test() {
assertNotNull(service); // Test succeeds
}
}
ExtendWith with both SpringExtension and MockitoExtension
@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
class TestServiceTest {
@MockBean
TestService service;
@Test
void test() {
assertNotNull(service); // Test succeeds
}
}
Both works in your case because of the @SpringBootTest annotation for the test class as explained.
To answer the question : When to use @ExtendWith Spring or Mockito? ,
When the test requires a Spring Test Context ( to autowire a bean / use of @MockBean ) along with JUnit 5’s Jupiter programming model use @ExtendWith(SpringExtension.class). This will support Mockito annotations as well through TestExecutionListeners.
When the test uses Mockito and needs JUnit 5’s Jupiter programming model support use @ExtendWith(MockitoExtension.class)
Hope this helps