Creating integration tests in a monolithic SpringBoot application

前端 未结 2 1463
情话喂你
情话喂你 2021-01-24 00:07

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 t

2条回答
  •  鱼传尺愫
    2021-01-24 00:22

    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.

提交回复
热议问题