chapter three

3 Configuring and running an application for testing

 

This chapter covers

  • How the @SpringBootTest annotation works
  • Accessing beans and properties in your tests
  • Configuring the application under test
  • Stubbing and mocking dependencies
  • Speeding up the tests by caching the test app

When you annotate a test class with @SpringBootTest, it automatically detects your application’s configuration, configures and optimizes it for a testing scenario, manages its lifecycle, and makes it accessible in your tests. You might need to update the configuration, for example, to stub out an external service that you don’t want to touch in your tests, as we saw in the previous chapter. You may have created several variants of your software based on user configuration, for example, with region-specific behavior controlled by properties or profiles, and want to run separate test suites for each. Or maybe you’d like to split your integration tests by logical modules and run only a subset of your application for each module.

Spring Boot Test has dedicated tooling for all of these use cases, from changing a few properties to manually selecting which components are loaded in your test application. Of course, there are important tradeoffs associated with customizing the application under test, and you should be aware of them when creating tests. Let’s dive in!

3.1 Understanding how the @SpringBootTest annotation works

3.2 Interacting with the application

3.3 Configuring the application under test

3.3.1 Changing configuration properties

3.3.2 Activating a profile

3.3.3 Adding configuration with @Configuration and @TestConfiguration

3.3.4 Building a test application from manually selected classes

3.4 Stubbing out dependencies by using mocks

3.5 Speeding up tests by reusing the ApplicationContext between tests

3.5.1 Using the Spring ContextCache

3.5.2 Avoiding creating too many test apps

3.5.3 Tradeoffs, side effects and limitations

3.6 Summary