Creating integration tests in a monolithic SpringBoot application

前端 未结 2 1464
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2021-01-24 00:24

    If you have to create spring integrations tests you have to : - invoke spring Context by using annotation on test class - for instance : @RunWith(SpringJUnit4ClassRunner.class) - use @MockBean or @SpyBean annotation on services that you are not going to test but they are part of testing methods/class - use @Autowired annotation on class that you are going to test. To verify results you can use Junit4 or Junit5 asserts and for verifying behavior you can use Mockito

    0 讨论(0)
提交回复
热议问题