Reputation: 1067
In unit test, what are the differences between @Runwith(SpringRunner.class)
& @SpringBootTest
?
Can you explain to me the use cases of each one?
Upvotes: 90
Views: 81687
Reputation: 1
Basically, SpringRunner @RunWith(SpringRunner.class) was a feature of JUnit4 and is not recommended anymore.
vs
@SpringBootTest is a feature of JUnit5. It's more performant, simpler to use and offers better configuration options. It's the recommended option if you have JUnit5 installed.
This article explains it : https://www.baeldung.com/springrunner-vs-springboottest
Upvotes: 0
Reputation: 731
@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
"If you are using JUnit 4, don’t forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there’s no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…Test annotations are already annotated with it.
Upvotes: 63
Reputation: 40048
@RunWith(SpringRunner.class) : You need this annotation to just enable spring boot features like @Autowire
, @MockBean
etc.. during junit testing
is used to provide a bridge between Spring Boot test features and JUnit. Whenever we are using any Spring Boot testing features in our JUnit tests, this annotation will be required.
@SpringBootTest : This annotation is used to load complete application context for end to end integration testing
The @SpringBootTest annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.
Here is the article with clear examples on both scenarios Baeldung
Upvotes: 125
Reputation: 712
From spring.io :
@RunWith(SpringRunner.class)
tells JUnit to run using Spring’s testing support.SpringRunner
is the new name forSpringJUnit4ClassRunner
, it’s just a bit easier on the eye.
@SpringBootTest
is saying “bootstrap with Spring Boot’s support” (e.g. loadapplication.properties
and give me all the Spring Boot goodness)
So if you don't need everything that Spring Boot loads for your integration test, you may not need @SpringBootTest
Upvotes: 17