user11705123
user11705123

Reputation: 633

What is the difference between @ExtendWith(SpringExtension.class) and @ExtendWith(MockitoExtension.class)?

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 ?

Upvotes: 46

Views: 35716

Answers (1)

Troley
Troley

Reputation: 1658

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).

Upvotes: 101

Related Questions