I was using @RunWith(MockitoJUnitRunner.class)
for my junit test with mockito. But now I am working with spring-boot and JUnit 5.
What's the difference between the two annotations ?
Can I use only @ExtendWith(SpringExtension.class)
to mock my objects ?
@RunWith is an old annotation from JUnit 4 to use test runners. If you're using JUnit 5 (Jupiter), you should use @ExtendWith to use JUnit extensions.
Class SpringExtension. SpringExtension integrates the Spring TestContext Framework into JUnit 5's Jupiter programming model. To use this extension, simply annotate a JUnit Jupiter based test class with @ExtendWith(SpringExtension.
@ExtendWith is a repeatable annotation that is used to register extensions for the annotated test class, test interface, test method, parameter, or field.
If you want to use Spring test framework features in your tests like for example @MockBean, then you have to use @ExtendWith (SpringExtension.class). It replaces the deprecated JUnit4 @RunWith (SpringJUnit4ClassRunner.class)
public class MockitoExtension extends java.lang.Object implements BeforeEachCallback, AfterEachCallback, ParameterResolver {..} As it can be seen , SpringExtension implements a lot more extensions than MockitoExtension.
When the test uses Mockito and needs JUnit 5's Jupiter programming model support use @ExtendWith (MockitoExtension.class) Show activity on this post.
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 involving Spring:
If you want to use Spring test framework features in your tests like for example @MockBean
, then you have to use @ExtendWith(SpringExtension.class)
. It replaces the deprecated JUnit4 @RunWith(SpringJUnit4ClassRunner.class)
When NOT involving Spring:
If you just want to involve Mockito and don't have to involve Spring, for example, when you just want to use the @Mock
/ @InjectMocks
annotations, then you want to use @ExtendWith(MockitoExtension.class)
, as it doesn't load in a bunch of unneeded Spring stuff. It replaces the deprecated JUnit4 @RunWith(MockitoJUnitRunner.class)
.
To answer your question:
Yes you can just use @ExtendWith(SpringExtension.class)
, but if you're not involving Spring test framework features in your tests, then you probably want to just use @ExtendWith(MockitoExtension.class)
.
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