Spring Boot test auto-configuration framework providing test slice annotations and infrastructure for focused integration testing
npx @tessl/cli install tessl/maven-org-springframework-boot--spring-boot-test-autoconfigure@4.0.0Test auto-configuration framework for focused, slice-based integration tests. Specialized annotations automatically configure only components needed for specific testing scenarios.
Group: org.springframework.boot | Artifact: spring-boot-test-autoconfigure | Version: 4.0.0 | Language: Java | Scope: test
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test-autoconfigure</artifactId>
<version>4.0.0</version>
<scope>test</scope>
</dependency>Gradle:
testImplementation 'org.springframework.boot:spring-boot-test-autoconfigure:4.0.0'The spring-boot-test-autoconfigure module depends on spring-boot-test, which has several optional dependencies that must be explicitly added for JSON testing to work:
Maven:
<!-- Required for JacksonTester -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>test</scope>
</dependency>
<!-- Required for JSON path assertions (.extractingJsonPathStringValue(), etc.) -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<!-- Required for JSON tester auto-configuration (@ConditionalOnJsonTesters) -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>Gradle:
testImplementation 'tools.jackson.core:jackson-databind'
testImplementation 'com.jayway.jsonpath:json-path'
testImplementation 'org.assertj:assertj-core'Note: All three dependencies are optional in spring-boot-test but required for JSON testing. Without these, JacksonTester will not work and tests will fail with NoClassDefFoundError.
// JSON Testing
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters;
import org.springframework.boot.test.autoconfigure.json.AutoConfigureJson;
// Test Infrastructure
import org.springframework.boot.test.autoconfigure.TestSliceTestContextBootstrapper;
import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
// Database Initialization
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureDataSourceInitialization;Test JSON serialization:
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@JsonTest
public class MyJsonTests {
@Autowired
private JacksonTester<MyObject> json;
@Test
public void testSerialize() throws Exception {
MyObject obj = new MyObject("test", 123);
assertThat(this.json.write(obj))
.extractingJsonPathStringValue("@.name")
.isEqualTo("test");
}
}Spring Boot Test AutoConfigure implements the test slice pattern to enable focused, fast integration tests. Understanding its architecture helps when using existing test slices or creating custom ones.
Test Slice Annotations (e.g., @JsonTest, @DataJpaTest)
TestSliceTestContextBootstrapper
Type Exclude Filters
Context Customizers
Auto-Configuration Control
| Annotation | Purpose | Common Usage | Auto-Configured Components |
|---|---|---|---|
@JsonTest | Test JSON serialization/deserialization | JSON marshal/unmarshal testing | JacksonTester, GsonTester, JsonbTester, BasicJsonTester |
@AutoConfigureJsonTesters | Enable JSON testers in any test | Add JSON testing to integration tests | Same as @JsonTest but without test slice isolation |
@AutoConfigureJson | Import JSON auto-configuration | Low-level JSON config without testers | Jackson/Gson/JSON-B auto-configuration |
@OverrideAutoConfiguration | Control auto-configuration loading | Disable default auto-config, enable specific ones | None - controls what gets loaded |
@AutoConfigureDataSourceInitialization | Initialize DataSource with SQL scripts | Enable schema.sql/data.sql execution | DataSourceInitializer |
@ConditionalOnJsonTesters | Conditional bean registration | Internal use in auto-configuration classes | N/A - conditional annotation |
Need to test JSON?
├─ YES: Need isolated JSON-only test?
│ ├─ YES: Use @JsonTest
│ └─ NO: Need JSON in broader test?
│ ├─ Need testers auto-configured?
│ │ ├─ YES: Use @SpringBootTest + @AutoConfigureJsonTesters
│ │ └─ NO: Use @SpringBootTest + @AutoConfigureJson
│ └─ Manual setup: Use @SpringBootTest only
└─ NO: Building custom test slice?
├─ YES: See Test Infrastructure section
└─ NO: Use standard @SpringBootTestTest JSON serialization/deserialization in isolation without full application context.
Loads: JSON testers (JacksonTester, GsonTester, JsonbTester, BasicJsonTester), Jackson/Gson/JSON-B auto-configuration, @JacksonComponent beans, JacksonModule implementations
Excludes: Web, database, security, and other auto-configurations
Imports:
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester; // from spring-boot-testUsage:
@JsonTest
public class UserJsonTests {
@Autowired
private JacksonTester<User> json;
@Test
public void serializeUser() throws Exception {
User user = new User("alice", "alice@example.com");
assertThat(this.json.write(user))
.extractingJsonPathStringValue("@.username")
.isEqualTo("alice");
}
@Test
public void deserializeUser() throws Exception {
String content = "{\"username\":\"alice\",\"email\":\"alice@example.com\"}";
User user = this.json.parse(content).getObject();
assertThat(user.getUsername()).isEqualTo("alice");
}
}Custom properties:
@JsonTest(properties = {
"spring.jackson.serialization.indent-output=true",
"spring.jackson.date-format=yyyy-MM-dd"
})
public class FormattedJsonTests {}Include additional components:
@JsonTest(includeFilters = @Filter(Component.class))
public class JsonTestWithComponents {}Exclude auto-configurations:
@JsonTest(excludeAutoConfiguration = SomeAutoConfiguration.class)
public class CustomJsonTests {}Complete JSON Testing Documentation
Create domain-specific test slice annotations that load only relevant components. Use for custom test annotations like @MyServiceTest, @MyRepositoryTest.
Imports:
import org.springframework.boot.test.autoconfigure.TestSliceTestContextBootstrapper;
import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;Pattern:
// 1. Create bootstrapper
public class MyServiceTestContextBootstrapper
extends TestSliceTestContextBootstrapper<MyServiceTest> {}
// 2. Create test annotation
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(MyServiceTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
@OverrideAutoConfiguration(enabled = false)
@ImportAutoConfiguration
public @interface MyServiceTest {
String[] properties() default {};
Class<?>[] excludeAutoConfiguration() default {};
}
// 3. Use the test slice
@MyServiceTest
public class MyFeatureTests {}Complete Test Infrastructure Documentation
Disable default auto-configuration and selectively import specific configurations. Use for precise control, performance-critical tests, or avoiding specific auto-configurations.
Imports:
import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;Disable all, import specific:
@SpringBootTest
@OverrideAutoConfiguration(enabled = false)
@ImportAutoConfiguration({
JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class
})
public class SelectiveConfigTest {}Use in custom test slice:
@OverrideAutoConfiguration(enabled = false)
@ImportAutoConfiguration // from META-INF/spring/*.imports
public @interface MyTest {}Execute schema.sql and data.sql scripts to initialize test database. Use for tests requiring pre-populated database state without @DataJpaTest.
Actions: Executes schema.sql (structure), data.sql (test data), supports platform-specific scripts (schema-h2.sql), respects spring.sql.init.* properties
Imports:
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureDataSourceInitialization;Usage:
@SpringBootTest
@AutoConfigureDataSourceInitialization
public class DatabaseTest {
@Autowired
private DataSource dataSource;
@Test
public void databaseInitialized() {} // schema.sql and data.sql executed
}Custom script locations:
@SpringBootTest(properties = {
"spring.sql.init.schema-locations=classpath:custom-schema.sql",
"spring.sql.init.data-locations=classpath:custom-data.sql"
})
@AutoConfigureDataSourceInitialization
public class CustomScriptsTest {}Note: Automatically included in @JdbcTest, @DataJpaTest, @JooqTest.
package org.springframework.boot.test.autoconfigure.json;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(JsonTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(JsonTypeExcludeFilter.class)
@AutoConfigureJsonTesters
@ImportAutoConfiguration
public @interface JsonTest {
String[] properties() default {};
boolean useDefaultFilters() default true;
Filter[] includeFilters() default {};
Filter[] excludeFilters() default {};
@AliasFor(annotation = ImportAutoConfiguration.class, attribute = "exclude")
Class<?>[] excludeAutoConfiguration() default {};
}Attributes:
properties: String[] — Test environment properties ("key=value")useDefaultFilters: boolean — Include only @JacksonComponent and JacksonModule beans (default: true)includeFilters: Filter[] — Additional component filtersexcludeFilters: Filter[] — Exclude specific beansexcludeAutoConfiguration: Class<?>[] — Exclude auto-configuration classesMeta-annotations:
@BootstrapWith(JsonTestContextBootstrapper.class) — JSON-specific test context bootstrapper@ExtendWith(SpringExtension.class) — Spring TestContext Framework with JUnit 5@OverrideAutoConfiguration(enabled = false) — Disables default auto-configuration@TypeExcludeFilters(JsonTypeExcludeFilter.class) — Limits scanning to JSON beans@AutoConfigureJsonTesters — Enables JSON tester auto-configuration@ImportAutoConfiguration — Imports from META-INF/spring imports filepackage org.springframework.boot.test.autoconfigure.json;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigureJson
@ImportAutoConfiguration
@PropertyMapping("spring.test.jsontesters")
public @interface AutoConfigureJsonTesters {
boolean enabled() default true;
}Attributes:
enabled: boolean — Enable/disable JSON tester bean registrationMeta-annotations:
@AutoConfigureJson — JSON library auto-configuration@ImportAutoConfiguration — Triggers auto-configuration import@PropertyMapping("spring.test.jsontesters") — Maps to spring.test.jsontesters.enabledpackage org.springframework.boot.test.autoconfigure.json;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ImportAutoConfiguration
public @interface AutoConfigureJson {
}Low-level annotation for JSON auto-configuration without tester setup. Prefer @JsonTest or @AutoConfigureJsonTesters.
package org.springframework.boot.test.autoconfigure.json;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ConditionalOnBooleanProperty("spring.test.jsontesters.enabled")
@ConditionalOnClass(name = "org.assertj.core.api.Assert")
public @interface ConditionalOnJsonTesters {
}Conditional for auto-configuration classes. Beans created only when:
spring.test.jsontesters.enabled is true (default)Internal use in JsonTestersAutoConfiguration.
package org.springframework.boot.test.autoconfigure;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OverrideAutoConfiguration {
boolean enabled();
}Attributes:
enabled: boolean — REQUIRED. Disable (false) or enable (true) default auto-configurationEffect: Sets spring.boot.enableautoconfiguration, overrides @EnableAutoConfiguration.
package org.springframework.boot.test.autoconfigure.jdbc;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ImportAutoConfiguration
public @interface AutoConfigureDataSourceInitialization {
}Triggers DataSourceInitializationAutoConfiguration import for SQL script execution.
Default locations: src/test/resources/schema.sql, data.sql, schema-${platform}.sql, data-${platform}.sql
package org.springframework.boot.test.autoconfigure;
public abstract class TestSliceTestContextBootstrapper<T extends Annotation>
extends SpringBootTestContextBootstrapper {
/**
* Create a new TestSliceTestContextBootstrapper instance.
* The constructor resolves the generic type parameter T from the subclass
* and stores it for property extraction from test annotations.
*/
protected TestSliceTestContextBootstrapper() {
// Internally resolves type parameter T and stores annotation type
}
/**
* Extract properties from the test slice annotation.
* Uses MergedAnnotations API to search the class hierarchy and extract
* the "properties" attribute from annotation T.
*
* @param testClass the test class
* @return the properties array from annotation T, or null if annotation not present
*/
@Override
protected String @Nullable [] getProperties(Class<?> testClass) {
// Searches class hierarchy for annotation T and extracts properties() attribute
}
}Type parameter: T — Test slice annotation type (e.g., JsonTest, WebMvcTest)
Methods:
getProperties(Class<?> testClass) — Override for custom property extractionUsage: Extend and specify custom test annotation as type parameter. Automatically extracts from properties() attribute.
package org.springframework.boot.test.autoconfigure.json;
@AutoConfiguration
@ConditionalOnJsonTesters
public final class JsonTestersAutoConfiguration {
// Package-private bean factory methods
// Registers bean post-processors for JSON tester initialization
}Auto-configuration for JSON tester factory beans. Active when @ConditionalOnJsonTesters conditions met.
Registered (internal): JsonTesterFieldInitializingBeanPostProcessor, JsonTesterFactoryBean instances
package org.springframework.boot.test.autoconfigure.json;
import org.jspecify.annotations.Nullable;
import org.springframework.beans.factory.FactoryBean;
public final class JsonTesterFactoryBean<T, M> implements FactoryBean<T> {
public JsonTesterFactoryBean(Class<?> objectType, @Nullable M marshaller);
@Override
public T getObject() throws Exception;
@Override
public Class<?> getObjectType();
@Override
public boolean isSingleton();
}Type parameters: T (tester: JacksonTester, GsonTester), M (marshaller: ObjectMapper, Gson)
Constructor: objectType (Class<?>), marshaller (M, nullable)
Internal factory bean for JSON tester instances.
package org.springframework.boot.test.autoconfigure.json;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.boot.test.json.AbstractJsonMarshalTester;
import org.jspecify.annotations.Nullable;
public abstract class JsonMarshalTesterRuntimeHints implements RuntimeHintsRegistrar {
/**
* Create a new JsonMarshalTesterRuntimeHints instance for the given tester class.
* @param tester the JSON marshal tester class
*/
protected JsonMarshalTesterRuntimeHints(
Class<? extends AbstractJsonMarshalTester> tester) {
// Stores tester class for hint registration
}
/**
* Register runtime hints for GraalVM native image.
* Registers reflection hints for the tester class declared constructors and the
* initialize(Class<?>, ResolvableType) method to enable JSON tester functionality
* in native images.
* @param hints the runtime hints instance
* @param classLoader the classloader, or null
*/
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
// Registers reflection hints for declared constructors and
// initialize(Class<?>, ResolvableType) method
}
}Registers GraalVM native image runtime hints for JSON testers. Ensures reflection works in native images.
Internal use. Subclasses: JacksonMarshalTesterRuntimeHints, GsonMarshalTesterRuntimeHints, JsonbMarshalTesterRuntimeHints.
| Property | Type | Default | Description |
|---|---|---|---|
| spring.test.jsontesters.enabled | boolean | true | Enable/disable JSON tester auto-configuration |
| spring.test.print-condition-evaluation-report | boolean | true | Print condition evaluation report on test context failure |
| spring.sql.init.schema-locations | String[] | classpath:schema.sql | SQL schema script locations |
| spring.sql.init.data-locations | String[] | classpath:data.sql | SQL data script locations |
| spring.sql.init.mode | enum | embedded | When to execute scripts: always, embedded, never |
| spring.sql.init.platform | String | all | Platform for SQL scripts (h2, postgresql, etc.) |
spring.test.jsontesters.enabled: falseOr: @JsonTest(properties = "spring.test.jsontesters.enabled=false")
spring.test.print-condition-evaluation-report: falseWhen true, prints detailed auto-configuration match report on ApplicationContext failures.
Status: DEPRECATED in 4.0.0
Deprecation level: error
Replacement: Use spring.test.metrics.export and spring.test.tracing.export
Do not use this property in new code.
Tester types available with @AutoConfigureJsonTesters (automatically initialized by BeanPostProcessor when library is available):
| Tester | Library | Module | Field Initialization |
|---|---|---|---|
| BasicJsonTester | None (requires json-path) | spring-boot-test | Always initialized |
| JacksonTester | jackson-databind | spring-boot-test | Initialized if Jackson available |
| GsonTester | gson | spring-boot-test | Initialized if Gson available |
| JsonbTester | JSON-B | spring-boot-test | Initialized if JSON-B available |
Multiple library usage:
@JsonTest
public class MultiLibraryTests {
@Autowired
private JacksonTester<User> jacksonJson; // Initialized if Jackson available
@Autowired(required = false)
private GsonTester<User> gsonJson; // Initialized if Gson available
@Test
public void testWithAvailableLibraries() {
// Fields are null if library not on classpath
if (jacksonJson != null) {
// Use jacksonJson
}
if (gsonJson != null) {
// Use gsonJson
}
}
}Symptom: JacksonTester field is null or NullPointerException when using it
Solutions:
Ensure @Autowired is used — JSON tester fields must be autowired:
@JsonTest
public class MyJsonTests {
@Autowired
private JacksonTester<MyType> json; // Correct - use @Autowired
}Missing library dependencies — Add all required dependencies:
<!-- Required for JacksonTester -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>test</scope>
</dependency>
<!-- Required for JSON path assertions -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<!-- Required for auto-configuration -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>Testers disabled — Enable: @JsonTest(properties = "spring.test.jsontesters.enabled=true")
Optional library — Check for null before using Gson/JSON-B testers:
if (gsonJson != null) {
// Use gsonJson
}Symptom: ApplicationContext fails with auto-configuration errors
Solutions:
Enable evaluation report — spring.test.print-condition-evaluation-report=true
Exclude conflicts — @JsonTest(excludeAutoConfiguration = ProblematicAutoConfiguration.class)
Check scanning — Verify TypeExcludeFilter not excluding needed beans
Symptom: schema.sql or data.sql not executed
Solutions:
Verify location — Scripts in src/test/resources/ (schema.sql, data.sql)
Check mode — spring.sql.init.mode: always (not 'never')
Add annotation — @AutoConfigureDataSourceInitialization on test class
Platform scripts — Use schema-h2.sql, schema-postgresql.sql if needed
Symptom: Custom test annotation doesn't load expected components
Solutions:
Verify bootstrapper — @BootstrapWith(MyCustomTestContextBootstrapper.class) on annotation
Check type parameter — extends TestSliceTestContextBootstrapper<MyCustomTest>
Verify imports file — Create META-INF/spring/org.springframework.boot.test.autoconfigure.MyCustomTest.imports
Check meta-annotation — Include @ImportAutoConfiguration
@SpringBootTest
@AutoConfigureJsonTesters
public class IntegrationTest {
private JacksonTester<User> json;
@Autowired
private UserService userService;
@Test
public void testServiceAndJson() throws Exception {
User user = userService.createUser("alice");
assertThat(json.write(user)).hasJsonPathValue("@.username");
}
}@SpringBootTest
@AutoConfigureJsonTesters
@AutoConfigureDataSourceInitialization
public class MultiLayerTest {}@JsonTest(properties = {
"spring.jackson.serialization.write-dates-as-timestamps=false",
"spring.jackson.serialization.indent-output=true",
"spring.jackson.default-property-inclusion=non_null"
})
public class ConfiguredJsonTest {}@JsonTest
public class CrossLibraryTest {
private JacksonTester<User> jacksonJson;
private GsonTester<User> gsonJson;
@Test
public void serializationConsistent() throws Exception {
User user = new User("alice");
String jacksonOutput = jacksonJson.write(user).getJson();
if (gsonJson != null) {
String gsonOutput = gsonJson.write(user).getJson();
}
}
}This module provides core infrastructure. Domain-specific test slices are in separate modules:
| Module | Test Annotation | Purpose | Key Components |
|---|---|---|---|
| spring-boot-test | @SpringBootTest | Full integration testing | @MockBean, @SpyBean, TestPropertyValues |
| spring-boot-web-test | @WebMvcTest | Spring MVC controller testing | MockMvc, @MockBean for services |
| spring-boot-web-test | @WebFluxTest | Spring WebFlux endpoint testing | WebTestClient |
| spring-boot-data-jpa-test | @DataJpaTest | JPA repository testing | TestEntityManager, embedded database |
| spring-boot-jdbc-test | @JdbcTest | JDBC component testing | JdbcTemplate, embedded database |
| spring-boot-data-mongo-test | @DataMongoTest | MongoDB repository testing | Embedded MongoDB |
| spring-boot-data-redis-test | @DataRedisTest | Redis testing | Embedded Redis |
| spring-boot-restclient-test | @RestClientTest | REST client testing | MockRestServiceServer |
Each builds on TestSliceTestContextBootstrapper infrastructure provided by this module.
FactoryBean<T>: Interface for bean factoriesBeanFactory: Spring bean factory interfaceTestContextBootstrapper: Base interface for test context bootstrappingContextCustomizer: Interface for customizing test application contextContextCustomizerFactory: Factory for creating context customizersSpringBootTestContextBootstrapper: Base bootstrapper for Spring Boot tests@SpringBootTest: Full integration test annotationBasicJsonTester: Basic JSON tester implementationJacksonTester<T>: Jackson-specific JSON testerGsonTester<T>: Gson-specific JSON testerJsonbTester<T>: JSON-B specific JSON testerAbstractJsonMarshalTester: Base class for marshal testersRuntimeHintsRegistrar: Interface for registering GraalVM native image hintsRuntimeHints: Container for runtime hintsAssert: AssertJ assertion base class (required for JSON tester auto-configuration)@Autowired(required = false) for Gson and JSON-B testersspring.test.print-condition-evaluation-report=true when troubleshooting