Skip to content

Spring Testing

Robin Drew edited this page May 27, 2025 · 19 revisions

Writing tests when developing a Spring application can be quite complicated. As Spring applications require the appropriate beans to be initialised

ContextConfiguration

ContextConfiguration - A class annotated with this can be considered a lightweight integration test. It is used to target loading specific configuration(s) for use in a test. It is a general Spring feature, and not specific to Spring Boot.

It does involve spring initialization so should be avoided where possible when writing tests, but it is less of an overhead that using @SpringBootTest.

SpringBootTest

SpringBootTest - A class annotated with this is an integration test. It will load the entire spring Application Context, and consequently will likely include a significant startup cost.

Integration tests should be run judiciously during development. Although it is essential to run them during the build pipeline, particularly before deployment in any environment, they should not be run routinely during day-to-day development.

The SpringBootTest annotation provides the following features:

  • Auto Configuration
  • Application Properties Loading
  • Component Scanning
  • Embedded Web Server Support

Spring Boot Starter Test Library

Maven Library \ spring-boot-starter-test

When writing spring boot tests, you will almost always want to include the Spring Boot Test Starter library. It provides support for the following libraries out-of-the-box:

  • Spring Test
  • JUnit
  • AssertJ
  • Hamcrest
  • Mockito
  • JSON
  • XML

This covers most of the standard testing libraries you will need.

Build Configuration

When adding test dependencies to a build, it is important to remember to restrict the scope of the dependencies to ensure no test libraries end up getting packaged in the deployment artifacts and just generally to promote loose coupling.

Maven Build Configuration

For Maven builds we use the scope tag to restrict libraries to tests.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

Gradle Build Configuration

For Gradle builds, we use the testImplementation configuration.

dependencies {
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.mockito:mockito-core:5.12.0")
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
}

Clone this wiki locally