1

How to write a proper test case for controller, service and Dao in spring boot using junit 5 with clear explanation

1 Answers1

0

Spring Boot has a concept of test slices. This type of test configuration will setup only a part of your application and thus making tests:

  • less likely to break on not-related change,
  • faster in comparison to configuring all application services (using @SpringBootTest annotation).

For example @JsonTest slice will configure ObjectMapper (and some test utilities for JSON) in the same way as it would happen on production.

Anyway, to your mentioned types:

  • DAO - use @DataJpaTest slice - it will configure Hibernate with in-memory database and load all your entities and repositories.
  • Controllers - use @WebMvcTest(YourController.class) slice - it will load only configuration for Spring MVC, advices and your controller. You will be responsible to deal with dependencies of that controller.
  • Services - pretty much depends on what is your service doing. I prefer using slices also for services depending on Spring-configured beans but your test can also be a very simple standard [j]unit test with all dependencies mocked away. - Depending on the compromise you want to make.

This does not change with the fifth version of junit. The only difference is that you no longer need to annotate your tests with @RunWith(SpringRunner.class).

Josef Cech
  • 2,115
  • 16
  • 17