or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdjson-testing.mdtest-infrastructure.md
tile.json

tessl/maven-org-springframework-boot--spring-boot-test-autoconfigure

Spring Boot test auto-configuration framework providing test slice annotations and infrastructure for focused integration testing

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.springframework.boot/spring-boot-test-autoconfigure@4.0.x

To install, run

npx @tessl/cli install tessl/maven-org-springframework-boot--spring-boot-test-autoconfigure@4.0.0

index.mddocs/

Spring Boot Test AutoConfigure

Test auto-configuration framework for focused, slice-based integration tests. Specialized annotations automatically configure only components needed for specific testing scenarios.

Package Information

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'

Additional Dependencies Required for JSON Testing

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.

Core Imports

// 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;

Quick Start

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");
    }
}

Architecture

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.

Key Components

Test Slice Annotations (e.g., @JsonTest, @DataJpaTest)

  • Composite annotations combining multiple Spring Testing annotations
  • Define what gets loaded (and excluded) for specific testing scenarios
  • Configured with custom bootstrappers and type filters

TestSliceTestContextBootstrapper

  • Base class for custom test context bootstrappers
  • Resolves generic type parameter to extract annotation metadata
  • Handles property extraction from test annotations
  • Extends SpringBootTestContextBootstrapper from spring-boot-test

Type Exclude Filters

  • Control component scanning in test slices
  • Filter which @Component, @Service, @Repository beans are loaded
  • Implement StandardAnnotationCustomizableTypeExcludeFilter pattern
  • Enable "slice" behavior by loading only relevant components

Context Customizers

  • Modify test ApplicationContext before refresh
  • Add properties, register beans, customize environment
  • Examples: OverrideAutoConfigurationContextCustomizerFactory, OnFailureConditionReportContextCustomizerFactory
  • Registered via META-INF/spring.factories

Auto-Configuration Control

  • @OverrideAutoConfiguration disables default auto-config
  • @ImportAutoConfiguration selectively imports needed configurations
  • META-INF/spring/*.imports files specify slice-specific auto-configurations
  • Enables minimal context loading for fast test execution

How Test Slices Work

  1. Annotation Processing: Test class annotated with test slice (e.g., @JsonTest)
  2. Bootstrapper Resolution: @BootstrapWith(JsonTestContextBootstrapper.class) specifies custom bootstrapper
  3. Auto-Config Override: @OverrideAutoConfiguration(enabled = false) disables default auto-config
  4. Type Filtering: @TypeExcludeFilters applies filter to limit component scanning
  5. Selective Import: @ImportAutoConfiguration loads only needed auto-configurations from META-INF/spring imports file
  6. Context Customization: ContextCustomizers modify context before refresh
  7. Test Execution: Lightweight ApplicationContext with only relevant components loaded

Benefits of Test Slice Architecture

  • Fast startup: Load only necessary components
  • Test isolation: Exclude unrelated parts of application
  • Focused testing: Test specific layers without full application context
  • Extensible: Create custom test slices for domain-specific scenarios
  • Reusable: Same infrastructure used across all Spring Boot test slices

Core Annotations Reference

AnnotationPurposeCommon UsageAuto-Configured Components
@JsonTestTest JSON serialization/deserializationJSON marshal/unmarshal testingJacksonTester, GsonTester, JsonbTester, BasicJsonTester
@AutoConfigureJsonTestersEnable JSON testers in any testAdd JSON testing to integration testsSame as @JsonTest but without test slice isolation
@AutoConfigureJsonImport JSON auto-configurationLow-level JSON config without testersJackson/Gson/JSON-B auto-configuration
@OverrideAutoConfigurationControl auto-configuration loadingDisable default auto-config, enable specific onesNone - controls what gets loaded
@AutoConfigureDataSourceInitializationInitialize DataSource with SQL scriptsEnable schema.sql/data.sql executionDataSourceInitializer
@ConditionalOnJsonTestersConditional bean registrationInternal use in auto-configuration classesN/A - conditional annotation

Decision Tree: Which Annotation to Use

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 @SpringBootTest

Primary Capabilities

1. JSON Testing with @JsonTest

Test 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-test

Usage:

@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

2. Custom Test Slices with TestSliceTestContextBootstrapper

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

3. Auto-Configuration Control with @OverrideAutoConfiguration

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 {}

4. DataSource Initialization with @AutoConfigureDataSourceInitialization

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.

API Reference

@JsonTest

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 filters
  • excludeFilters: Filter[] — Exclude specific beans
  • excludeAutoConfiguration: Class<?>[] — Exclude auto-configuration classes

Meta-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 file

@AutoConfigureJsonTesters

package 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 registration

Meta-annotations:

  • @AutoConfigureJson — JSON library auto-configuration
  • @ImportAutoConfiguration — Triggers auto-configuration import
  • @PropertyMapping("spring.test.jsontesters") — Maps to spring.test.jsontesters.enabled

@AutoConfigureJson

package 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.

@ConditionalOnJsonTesters

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:

  1. spring.test.jsontesters.enabled is true (default)
  2. AssertJ on classpath

Internal use in JsonTestersAutoConfiguration.

@OverrideAutoConfiguration

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-configuration

Effect: Sets spring.boot.enableautoconfiguration, overrides @EnableAutoConfiguration.

@AutoConfigureDataSourceInitialization

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

TestSliceTestContextBootstrapper<T>

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 extraction

Usage: Extend and specify custom test annotation as type parameter. Automatically extracts from properties() attribute.

JsonTestersAutoConfiguration

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

JsonTesterFactoryBean<T, M>

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.

JsonMarshalTesterRuntimeHints

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.

Configuration Properties

PropertyTypeDefaultDescription
spring.test.jsontesters.enabledbooleantrueEnable/disable JSON tester auto-configuration
spring.test.print-condition-evaluation-reportbooleantruePrint condition evaluation report on test context failure
spring.sql.init.schema-locationsString[]classpath:schema.sqlSQL schema script locations
spring.sql.init.data-locationsString[]classpath:data.sqlSQL data script locations
spring.sql.init.modeenumembeddedWhen to execute scripts: always, embedded, never
spring.sql.init.platformStringallPlatform for SQL scripts (h2, postgresql, etc.)

spring.test.jsontesters.enabled

spring.test.jsontesters.enabled: false

Or: @JsonTest(properties = "spring.test.jsontesters.enabled=false")

spring.test.print-condition-evaluation-report

spring.test.print-condition-evaluation-report: false

When true, prints detailed auto-configuration match report on ApplicationContext failures.

spring.test.observability.auto-configure (DEPRECATED)

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.

JSON Tester Types

Tester types available with @AutoConfigureJsonTesters (automatically initialized by BeanPostProcessor when library is available):

TesterLibraryModuleField Initialization
BasicJsonTesterNone (requires json-path)spring-boot-testAlways initialized
JacksonTesterjackson-databindspring-boot-testInitialized if Jackson available
GsonTestergsonspring-boot-testInitialized if Gson available
JsonbTesterJSON-Bspring-boot-testInitialized 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
        }
    }
}

Troubleshooting

JSON Tester Field is Null

Symptom: JacksonTester field is null or NullPointerException when using it

Solutions:

  1. Ensure @Autowired is used — JSON tester fields must be autowired:

    @JsonTest
    public class MyJsonTests {
        @Autowired
        private JacksonTester<MyType> json;  // Correct - use @Autowired
    }
  2. 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>
  3. Testers disabled — Enable: @JsonTest(properties = "spring.test.jsontesters.enabled=true")

  4. Optional library — Check for null before using Gson/JSON-B testers:

    if (gsonJson != null) {
        // Use gsonJson
    }

Test Context Fails to Start

Symptom: ApplicationContext fails with auto-configuration errors

Solutions:

  1. Enable evaluation reportspring.test.print-condition-evaluation-report=true

  2. Exclude conflicts@JsonTest(excludeAutoConfiguration = ProblematicAutoConfiguration.class)

  3. Check scanning — Verify TypeExcludeFilter not excluding needed beans

DataSource Initialization Scripts Not Executed

Symptom: schema.sql or data.sql not executed

Solutions:

  1. Verify location — Scripts in src/test/resources/ (schema.sql, data.sql)

  2. Check modespring.sql.init.mode: always (not 'never')

  3. Add annotation — @AutoConfigureDataSourceInitialization on test class

  4. Platform scripts — Use schema-h2.sql, schema-postgresql.sql if needed

Custom Test Slice Not Working

Symptom: Custom test annotation doesn't load expected components

Solutions:

  1. Verify bootstrapper@BootstrapWith(MyCustomTestContextBootstrapper.class) on annotation

  2. Check type parameterextends TestSliceTestContextBootstrapper<MyCustomTest>

  3. Verify imports file — Create META-INF/spring/org.springframework.boot.test.autoconfigure.MyCustomTest.imports

  4. Check meta-annotation — Include @ImportAutoConfiguration

Integration Patterns

JSON Testing in Integration Tests

@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");
    }
}

Combining Multiple Test Slices

@SpringBootTest
@AutoConfigureJsonTesters
@AutoConfigureDataSourceInitialization
public class MultiLayerTest {}

Custom Properties

@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 {}

Testing Multiple JSON Libraries

@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();
        }
    }
}

Related Spring Boot Test Modules

This module provides core infrastructure. Domain-specific test slices are in separate modules:

ModuleTest AnnotationPurposeKey Components
spring-boot-test@SpringBootTestFull integration testing@MockBean, @SpyBean, TestPropertyValues
spring-boot-web-test@WebMvcTestSpring MVC controller testingMockMvc, @MockBean for services
spring-boot-web-test@WebFluxTestSpring WebFlux endpoint testingWebTestClient
spring-boot-data-jpa-test@DataJpaTestJPA repository testingTestEntityManager, embedded database
spring-boot-jdbc-test@JdbcTestJDBC component testingJdbcTemplate, embedded database
spring-boot-data-mongo-test@DataMongoTestMongoDB repository testingEmbedded MongoDB
spring-boot-data-redis-test@DataRedisTestRedis testingEmbedded Redis
spring-boot-restclient-test@RestClientTestREST client testingMockRestServiceServer

Each builds on TestSliceTestContextBootstrapper infrastructure provided by this module.

External Type Dependencies

From org.springframework.beans.factory (Spring Framework)

  • FactoryBean<T>: Interface for bean factories
  • BeanFactory: Spring bean factory interface

From org.springframework.test.context (Spring Framework)

  • TestContextBootstrapper: Base interface for test context bootstrapping
  • ContextCustomizer: Interface for customizing test application context
  • ContextCustomizerFactory: Factory for creating context customizers

From org.springframework.boot.test.context (spring-boot-test)

  • SpringBootTestContextBootstrapper: Base bootstrapper for Spring Boot tests
  • @SpringBootTest: Full integration test annotation

From org.springframework.boot.test.json (spring-boot-test)

  • BasicJsonTester: Basic JSON tester implementation
  • JacksonTester<T>: Jackson-specific JSON tester
  • GsonTester<T>: Gson-specific JSON tester
  • JsonbTester<T>: JSON-B specific JSON tester
  • AbstractJsonMarshalTester: Base class for marshal testers

From org.springframework.aot.hint (Spring Framework)

  • RuntimeHintsRegistrar: Interface for registering GraalVM native image hints
  • RuntimeHints: Container for runtime hints

From org.assertj.core.api (AssertJ)

  • Assert: AssertJ assertion base class (required for JSON tester auto-configuration)

Version Compatibility

  • Spring Framework: Requires 7.x (part of Spring Boot 4.x)
  • JUnit: Works with JUnit 5 (Jupiter) via @ExtendWith
  • Java: Requires Java 17+ (Spring Boot 4.0 baseline)
  • GraalVM: Native image support via RuntimeHintsRegistrar implementations

Best Practices for Agents

  1. Use appropriate test scope: Choose @JsonTest for isolated JSON testing, not @SpringBootTest
  2. Minimize auto-configuration: Use @OverrideAutoConfiguration(enabled = false) + selective imports for performance
  3. Handle optional libraries: Always use @Autowired(required = false) for Gson and JSON-B testers
  4. Leverage test slices: Create custom test slices for recurring test patterns in the codebase
  5. Enable debugging: Set spring.test.print-condition-evaluation-report=true when troubleshooting
  6. Use platform-specific scripts: Name SQL scripts with platform suffix (schema-h2.sql) for clarity
  7. Check library availability: Before using a tester, verify the JSON library is on the test classpath
  8. Preserve test isolation: Avoid loading unnecessary auto-configurations that increase startup time