https://reflectoring.io/spring-boot-test/

0018-cogs-1200x628-branded.jpg

With the @SpringBootTest annotation, Spring Boot provides a convenient way to start up an application context to be used in a test. In this tutorial, we’ll discuss when to use @SpringBootTest and when to better use other tools for testing. We’ll also look into different ways to customize the application context and how to reduce test runtime.

This article is accompanied by a working code example on GitHub.

The “Testing with Spring Boot” Series

This tutorial is part of a series:

If you like learning from videos, make sure to check out Philip’s Testing Spring Boot Applications Masterclass (if you buy through this link, I get a cut).

Dependencies

The code examples in this article only need the dependencies to Spring Boot’s test starter and to JUnit Jupiter:

dependencies {
	testCompile('org.springframework.boot:spring-boot-starter-test')
	testCompile('org.junit.jupiter:junit-jupiter:5.4.0')
}

Integration Tests vs. Unit Tests

Before we start into integration tests with Spring Boot, let’s define what sets an integration test apart from a unit test.

A unit test covers a single “unit”, where a unit commonly is a single class, but can also be a cluster of cohesive classes that is tested in combination.

An integration test can be any of the following:

Spring Boot provides the @SpringBootTest annotation which we can use to create an application context containing all the objects we need for all of the above test types. Note, however, that overusing @SpringBootTest might lead to very long-running test suites.

So, for simple tests that cover multiple units we should rather create plain tests, very similar to unit tests, in which we manually create the object graph needed for the test and mock away the rest. This way, Spring doesn’t fire up a whole application context each time the test is started.