Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringRunner vs SpringBootTest

In unit test, what are the differences between @Runwith(SpringRunner.class) & @SpringBootTest?

Can you explain to me the use cases of each one?

like image 640
zouari Avatar asked Nov 17 '19 14:11

zouari


People also ask

When should we use @SpringBootTest?

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. Show activity on this post. "If you are using JUnit 4, don't forget to also add @RunWith(SpringRunner.

What is @SpringRunner?

SpringRunner is an alias for the SpringJUnit4ClassRunner , which joins JUnit testing library with the Spring TestContext Framework. We use it with @RunWith(SpringRunner. class) . With SpringRunner , we can implement standard JUnit 4-based unit and integration tests.

What is the difference between SpringJUnit4ClassRunner and SpringRunner?

There is no difference, from the javadoc: SpringRunner is an alias for the SpringJUnit4ClassRunner.

What does SpringBootTest annotation do?

The @SpringBootTest annotation loads the complete Spring application context. In contrast, a test slice annotation only loads beans required to test a particular layer. And because of this, we can avoid unnecessary mocking and side effects.


2 Answers

@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

like image 56
Deadpool Avatar answered Sep 28 '22 08:09

Deadpool


@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

See https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing

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

like image 39
Tore Gard at techpros no Avatar answered Sep 28 '22 06:09

Tore Gard at techpros no