Creating integration tests in a monolithic SpringBoot application

João Matos :

I was asked to create an integration test for a service within a very large SpringBoot project yielding dozens of implemented services. When the application is executed all of these services are deployed - I want to avoid deploying all services unrelated with the one for which I'm creating the test. Unfortunately, I do not (yet) have as much experience with spring boot tests as I would hope for hence I was wondering what is the best approach to address this.

I was thinking about annotating all unrelated services with @MockBean annotation and all related ones with @Autowire inside the test class, but I'm not sure if this is the proper way to go. Can anyone point me in the right direction?

Thank you.

Josef :

The answer largely depends on the scope of your integration test. I will try to cover two main ways and you can google your wait our for more examples and details. Spring Boot testing documentation is also your friend.

Slices

Spring Boot provides test utilities called slices. For example there's a slice for testing your controllers - @WebMvcTest - this test will load all configuration for calling your application from HTTP and your specified controller (@WebMvcTest(YourController.class)). After that you need to decide what to do with dependencies of that controller.

You can:

  • Mock them with @MockBean.
  • Provide real implementation (or additional configuration) with @Import (and then you have to again deal with dependencies of the newly imported dependency).
  • Load additional part of Spring Boot auto-configuration. This can be done using @AutoConfigureSomething annotations. - All slices are basically composites of autoconfigure annotations and you are free to add them to your tests. For example have a look at annotations on DataJpaTest for what it takes to add capability to setup Spring Boot Data JPA with test database.

You can have maximum one slice per your test but you can import any number of additional services, configurations, mocks, auto-configurations etc. The point is - you choose what is configured for your test; new unrelated services with new dependencies should not break existing tests.

SpringBootTest

Another approach is @SpringBootTest annotation - this goes in the opposite direction - by default it loads everything and you can exclude stuff you don't want with @MockBean, @EnableAutoConfiguration(exclude=SomeClass) etc.

There's of course a danger of breaking existing tests when adding new services. - This should not happen too often as everything is configured automatically but it's still a possibility especially in monolith with more configuration.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421086&siteId=1