CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Spring TestContext Framework for comprehensive integration testing of Spring applications

Overview
Eval results
Files

testing-annotations.mddocs/

Testing Annotations

Spring Test provides a comprehensive set of annotations for configuring test behavior, context loading, and transaction management. These annotations enable declarative configuration of test scenarios and integration with the Spring TestContext Framework.

Capabilities

Context Configuration Annotations

Annotations for configuring the ApplicationContext in Spring tests.

/**
 * @TestPropertySource configures the locations of properties files and inlined properties 
 * to be added to the Environment's set of PropertySources for an ApplicationContext.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface TestPropertySource {
    
    /**
     * Alias for locations().
     * @return an array of resource locations for properties files
     */
    @AliasFor("locations")
    String[] value() default {};
    
    /**
     * The resource locations of properties files to be loaded into the Environment's PropertySources.
     * @return an array of resource locations
     */
    @AliasFor("value")  
    String[] locations() default {};
    
    /**
     * Inlined properties in the form of key=value pairs to be added to the Environment's PropertySources.
     * @return an array of inlined properties
     */
    String[] properties() default {};
    
    /**
     * Whether or not test property source locations should be inherited from superclasses.
     * @return true if locations should be inherited
     */
    boolean inheritLocations() default true;
    
    /**
     * Whether or not inlined test properties should be inherited from superclasses.
     * @return true if properties should be inherited
     */
    boolean inheritProperties() default true;
    
    /**
     * The application context resource loading factory class to use.
     * @return the factory class
     */
    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}

/**
 * @DynamicPropertySource is a method-level annotation that can be used to register 
 * dynamic properties to be added to the Environment's set of PropertySources.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DynamicPropertySource {
    
    /**
     * The name of the dynamic property source.
     * @return the property source name
     */
    String value() default "";
}

/**
 * @WebAppConfiguration is a class-level annotation that is used to declare that 
 * the ApplicationContext loaded for an integration test should be a WebApplicationContext.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface WebAppConfiguration {
    
    /**
     * The resource path to the root of the web application.
     * @return the resource path
     */
    String value() default "src/main/webapp";
}

/**
 * @BootstrapWith is a class-level annotation that is used to configure how the 
 * Spring TestContext Framework is bootstrapped.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface BootstrapWith {
    
    /**
     * The TestContextBootstrapper to use to bootstrap the TestContext Framework.
     * @return the TestContextBootstrapper class
     */
    Class<? extends TestContextBootstrapper> value() default TestContextBootstrapper.class;
}

Test Execution Annotations

Annotations for controlling test execution behavior and lifecycle.

/**
 * @DirtiesContext indicates that the underlying Spring ApplicationContext has been 
 * dirtied during the execution of a test and should be closed and removed from the context cache.
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DirtiesContext {
    
    /**
     * The mode to use when a test method is annotated with @DirtiesContext.
     * @return the method mode
     */
    MethodMode methodMode() default MethodMode.AFTER_METHOD;
    
    /**
     * The mode to use when a test class is annotated with @DirtiesContext.
     * @return the class mode
     */
    ClassMode classMode() default ClassMode.AFTER_CLASS;
    
    /**
     * The context hierarchy mode to use when @DirtiesContext is present on a test class.
     * @return the hierarchy mode
     */
    HierarchyMode hierarchyMode() default HierarchyMode.EXHAUSTIVE;
    
    /**
     * Defines modes which determine when a test class's ApplicationContext should be marked as dirty.
     */
    enum ClassMode {
        
        /**
         * The associated ApplicationContext will be marked as dirty before the test class.
         */
        BEFORE_CLASS,
        
        /**
         * The associated ApplicationContext will be marked as dirty before each test method in the class.
         */
        BEFORE_EACH_TEST_METHOD,
        
        /**
         * The associated ApplicationContext will be marked as dirty after each test method in the class.
         */
        AFTER_EACH_TEST_METHOD,
        
        /**
         * The associated ApplicationContext will be marked as dirty after the test class.
         */
        AFTER_CLASS
    }
    
    /**
     * Defines modes which determine when a test method's ApplicationContext should be marked as dirty.
     */
    enum MethodMode {
        
        /**
         * The associated ApplicationContext will be marked as dirty before the test method.
         */
        BEFORE_METHOD,
        
        /**
         * The associated ApplicationContext will be marked as dirty after the test method.
         */
        AFTER_METHOD
    }
    
    /**
     * Defines modes which determine how @DirtiesContext is interpreted when used in a test class hierarchy.
     */
    enum HierarchyMode {
        
        /**
         * The ApplicationContext will be removed from the context cache along with all other 
         * contexts in the same hierarchy.
         */
        EXHAUSTIVE,
        
        /**
         * Only the ApplicationContext of the current level in the context hierarchy will be removed from the context cache.
         */
        CURRENT_LEVEL
    }
}

/**
 * @TestExecutionListeners defines class-level metadata for configuring which 
 * TestExecutionListeners should be registered with the TestContextManager.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface TestExecutionListeners {
    
    /**
     * The TestExecutionListeners to register with the TestContextManager.
     * @return an array of TestExecutionListener classes
     */
    Class<? extends TestExecutionListener>[] value() default {};
    
    /**
     * Alias for value().
     * @return an array of TestExecutionListener classes
     */
    @AliasFor("value")
    Class<? extends TestExecutionListener>[] listeners() default {};
    
    /**
     * Whether or not TestExecutionListeners from superclasses should be inherited.
     * @return true if listeners should be inherited
     */
    boolean inheritListeners() default true;
    
    /**
     * The merge mode to use when @TestExecutionListeners is declared on a class 
     * that does not inherit listeners from a superclass.
     * @return the merge mode
     */
    MergeMode mergeMode() default MergeMode.REPLACE_DEFAULTS;
    
    /**
     * Enumeration of modes that dictate whether explicitly declared listeners are 
     * merged with the default listeners when @TestExecutionListeners is declared on a class.
     */
    enum MergeMode {
        
        /**
         * Locally declared listeners should be merged with the default listeners.
         */
        MERGE_WITH_DEFAULTS,
        
        /**
         * Locally declared listeners should replace the default listeners.
         */
        REPLACE_DEFAULTS
    }
}

/**
 * @RecordApplicationEvents is a class-level annotation that is used to instruct the 
 * Spring TestContext Framework to record all application events that are published 
 * in the ApplicationContext during the execution of a single test.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RecordApplicationEvents {
}

Transaction Annotations

Annotations for controlling transactional behavior in tests.

/**
 * @Transactional can be used to configure transactional test methods to run within a transaction.
 * When used at the class level, it establishes default transaction semantics for all test methods.
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Transactional {
    
    /**
     * Alias for transactionManager().
     * @return the transaction manager bean name
     */
    @AliasFor("transactionManager")
    String value() default "";
    
    /**
     * The bean name of the PlatformTransactionManager that should be used to drive transactions.
     * @return the transaction manager bean name
     */
    @AliasFor("value")
    String transactionManager() default "";
    
    /**
     * The transaction propagation type.
     * @return the propagation type
     */
    Propagation propagation() default Propagation.REQUIRED;
    
    /**
     * The transaction isolation level.
     * @return the isolation level
     */
    Isolation isolation() default Isolation.DEFAULT;
    
    /**
     * The timeout for this transaction (in seconds).
     * @return the timeout value
     */
    int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;
    
    /**
     * The timeout for this transaction (in seconds).
     * @return the timeout value as a String
     */
    String timeoutString() default "";
    
    /**
     * A boolean flag that can be set to true if the transaction is effectively read-only.
     * @return true if the transaction is read-only
     */
    boolean readOnly() default false;
    
    /**
     * Defines zero or more exception classes, which must be subclasses of Throwable, 
     * indicating which exception types must cause a transaction rollback.
     * @return an array of exception classes
     */
    Class<? extends Throwable>[] rollbackFor() default {};
    
    /**
     * Defines zero or more exception class names (for exceptions which must be subclasses of Throwable) 
     * indicating which exception types must cause a transaction rollback.
     * @return an array of exception class names
     */
    String[] rollbackForClassName() default {};
    
    /**
     * Defines zero or more exception classes, which must be subclasses of Throwable, 
     * indicating which exception types must not cause a transaction rollback.
     * @return an array of exception classes
     */
    Class<? extends Throwable>[] noRollbackFor() default {};
    
    /**
     * Defines zero or more exception class names (for exceptions which must be subclasses of Throwable) 
     * indicating which exception types must not cause a transaction rollback.
     * @return an array of exception class names
     */
    String[] noRollbackForClassName() default {};
}

/**
 * @Rollback indicates whether the transaction for a transactional test method should be rolled back 
 * after the test method has completed.
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Rollback {
    
    /**
     * Whether the transaction should be rolled back after the test has completed.
     * @return true if the transaction should be rolled back
     */
    boolean value() default true;
}

/**
 * @Commit indicates that the transaction for a transactional test method should be committed 
 * after the test method has completed.
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Commit {
}

Test Method Annotations

Annotations for individual test method configuration and execution control.

/**
 * @Repeat indicates that the annotated test method should be executed repeatedly.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Repeat {
    
    /**
     * The number of times that the annotated test method should be repeated.
     * @return the repeat count
     */
    int value() default 1;
}

/**
 * @Timed indicates that the annotated test method must finish execution in a specified time period.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Timed {
    
    /**
     * The maximum amount of time (in milliseconds) that the test execution can take 
     * without being marked as failed due to taking too long.
     * @return the timeout in milliseconds
     */
    long millis() default 0L;
}

/**
 * @IfProfileValue indicates that the annotated test is enabled for a specific testing environment.
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface IfProfileValue {
    
    /**
     * The name of the profile value against which to test.
     * @return the profile value name
     */
    String name() default "";
    
    /**
     * The expected value of the named profile value.
     * @return the expected value
     */
    String value() default "";
    
    /**
     * A list of all expected values for the named profile value.
     * @return an array of expected values
     */
    String[] values() default {};
}

/**
 * @ProfileValueSourceConfiguration is a class-level annotation that is used to specify 
 * what type of ProfileValueSource to use when retrieving profile values configured via @IfProfileValue.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ProfileValueSourceConfiguration {
    
    /**
     * The type of ProfileValueSource to use when retrieving profile values.
     * @return the ProfileValueSource class
     */
    Class<? extends ProfileValueSource> value() default SystemProfileValueSource.class;
}

Usage Examples:

import org.springframework.test.annotation.*;
import org.springframework.test.context.*;
import org.springframework.transaction.annotation.Transactional;

// Basic test configuration
@SpringJUnitConfig(TestConfig.class)
@TestPropertySource(locations = "/test.properties", 
                   properties = {"app.name=TestApp", "debug=true"})
@ActiveProfiles("test")
class UserServiceTest {
    
    @Autowired
    private UserService userService;
    
    @Test
    @Transactional
    @Rollback
    void shouldCreateUserInTransaction() {
        User user = new User("John", "john@example.com");
        User saved = userService.save(user);
        assertThat(saved.getId()).isNotNull();
        // Transaction will be rolled back
    }
    
    @Test
    @Transactional
    @Commit
    void shouldCommitUserCreation() {
        User user = new User("Jane", "jane@example.com");
        userService.save(user);
        // Transaction will be committed
    }
}

// Dynamic property configuration
@SpringJUnitConfig(DatabaseTestConfig.class)
class DatabaseIntegrationTest {
    
    @DynamicPropertySource
    static void configureDatabaseProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", () -> database.getJdbcUrl());
        registry.add("spring.datasource.username", database::getUsername);
        registry.add("spring.datasource.password", database::getPassword);
    }
    
    @Test
    void shouldConnectToDatabase() {
        // Test with dynamic database configuration
    }
}

// Context dirtying scenarios
@SpringJUnitConfig(CacheTestConfig.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class CacheIntegrationTest {
    
    @Autowired
    private CacheManager cacheManager;
    
    @Test
    void shouldCacheData() {
        // Test caching behavior
        // Context will be marked dirty after this method
    }
    
    @Test
    @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
    void shouldStartWithCleanCache() {
        // Context will be marked dirty before this method
        // Test with fresh cache
    }
}

// Web application configuration
@SpringJUnitWebConfig(WebConfig.class)
@WebAppConfiguration("src/test/webapp")
class WebControllerTest {
    
    @Autowired
    private WebApplicationContext webContext;
    
    @Autowired
    private MockMvc mockMvc;
    
    @Test
    void shouldLoadWebContext() {
        assertThat(webContext).isNotNull();
        assertThat(webContext.getServletContext()).isNotNull();
    }
}

// Profile-based conditional execution
@SpringJUnitConfig(ProfileTestConfig.class)
@ProfileValueSourceConfiguration(SystemProfileValueSource.class)
class ConditionalTest {
    
    @Test
    @IfProfileValue(name = "test.environment", value = "integration")
    void shouldRunOnlyInIntegrationEnvironment() {
        // This test runs only when system property test.environment=integration
    }
    
    @Test
    @IfProfileValue(name = "os.name", values = {"Linux", "Mac OS X"})
    void shouldRunOnUnixSystems() {
        // This test runs only on specified operating systems
    }
}

// Repeated execution and timing
@SpringJUnitConfig(PerformanceTestConfig.class)
class PerformanceTest {
    
    @Test
    @Repeat(5)
    @Timed(millis = 1000)
    void shouldCompleteWithin1Second() {
        // This test will be repeated 5 times and must complete within 1 second each time
        performanceService.executeOperation();
    }
}

// Event recording
@SpringJUnitConfig(EventTestConfig.class)
@RecordApplicationEvents
class EventPublishingTest {
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    
    @Autowired
    private ApplicationEvents events;
    
    @Test
    void shouldRecordPublishedEvents() {
        eventPublisher.publishEvent(new UserCreatedEvent("John"));
        eventPublisher.publishEvent(new UserUpdatedEvent("John"));
        
        assertThat(events.stream(UserCreatedEvent.class)).hasSize(1);
        assertThat(events.stream(UserUpdatedEvent.class)).hasSize(1);
        assertThat(events.stream().count()).isEqualTo(2);
    }
}

// Custom test execution listeners
@SpringJUnitConfig(CustomTestConfig.class)
@TestExecutionListeners(
    listeners = {CustomTestExecutionListener.class, MetricsCollectionListener.class},
    mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS
)
class CustomExecutionTest {
    
    @Test
    void shouldUseCustomListeners() {
        // Test will execute with custom listeners in addition to default ones
    }
}

Types

/**
 * Strategy interface for providing profile values programmatically.
 */
public interface ProfileValueSource {
    
    /**
     * Get the profile value indicated by the specified key.
     * @param key the name of the profile value
     * @return the String value of the profile value, or null if there is no value with that key
     */
    @Nullable
    String get(String key);
}

/**
 * Default implementation of ProfileValueSource which resolves system properties 
 * and system environment variables.
 */
public class SystemProfileValueSource implements ProfileValueSource {
    
    /**
     * Get the profile value for the given key from system properties, 
     * falling back to environment variables if not found.
     * @param key the profile value key
     * @return the profile value, or null if not found
     */
    @Nullable
    @Override
    public String get(String key);
}

/**
 * Registry for dynamic properties to be added to the Environment during test execution.
 */
public interface DynamicPropertyRegistry {
    
    /**
     * Add a dynamic property with the given name and Supplier of the value.
     * @param name the property name
     * @param valueSupplier a supplier for the property value
     */
    void add(String name, Supplier<Object> valueSupplier);
    
    /**
     * Add a dynamic property with the given name and value.
     * @param name the property name  
     * @param value the property value
     */
    void add(String name, Object value);
}

/**
 * ApplicationEvents encapsulates all ApplicationEvents that were published 
 * during the execution of a single test and provides methods to interact with those events.
 */
public interface ApplicationEvents {
    
    /**
     * Get a stream of all application events of the specified type that were published during test execution.
     * @param type the event type
     * @param <T> the event type
     * @return a stream of events of the specified type
     */
    <T extends ApplicationEvent> Stream<T> stream(Class<T> type);
    
    /**
     * Get a stream of all application events that were published during test execution.
     * @return a stream of all events
     */
    Stream<ApplicationEvent> stream();
    
    /**
     * Clear all recorded events.
     */
    void clear();
}

### Additional Testing Annotations

Key annotations for advanced test configuration and execution control.

```java { .api }
/**
 * @RecordApplicationEvents indicates that ApplicationEvents published in the ApplicationContext 
 * should be recorded and made available to the test via ApplicationEvents.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RecordApplicationEvents {
}

/**
 * @DisabledInAotMode indicates that the annotated test class or test method should be disabled 
 * when running in AOT (ahead-of-time) processing mode.
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DisabledInAotMode {
    
    /**
     * The reason this test is disabled in AOT mode.
     * @return the reason for disabling in AOT mode
     */
    String value() default "";
}

/**
 * @NestedTestConfiguration indicates how test configuration should be handled for @Nested test classes.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface NestedTestConfiguration {
    
    /**
     * The nested test configuration mode.
     * @return the configuration mode
     */
    EnclosingConfiguration value();
    
    /**
     * Enum defining nested test configuration behavior.
     */
    enum EnclosingConfiguration {
        /**
         * Inherit configuration from the enclosing test class.
         */
        INHERIT,
        
        /**
         * Override configuration from the enclosing test class.
         */
        OVERRIDE
    }
}

/**
 * @DynamicPropertySource can be used to register dynamic properties to be added to 
 * the Environment's set of PropertySources for an ApplicationContext loaded for an integration test.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DynamicPropertySource {
    
    /**
     * The name that can be used to reference this dynamic property source.
     * @return the name for this property source
     */
    String value() default "";
}

Types

/**
 * Functional interface for dynamic property registration.
 */
@FunctionalInterface
public interface DynamicPropertyRegistry {
    
    /**
     * Add a Supplier for the given property name to this registry.
     * @param name the property name
     * @param valueSupplier the supplier for the property value
     */
    void add(String name, Supplier<Object> valueSupplier);
}

/**

  • Utility class for working with test annotations. */ public abstract class TestAnnotationUtils {

    /**

    • Get the repeat count for the specified test method.
    • @param testMethod the test method
    • @return the repeat count, or 1 if no @Repeat annotation is present */ public static int getRepeatCount(Method testMethod);

    /**

    • Get the timeout for the specified test method.
    • @param testMethod the test method
    • @return the timeout in milliseconds, or 0 if no @Timed annotation is present */ public static long getTimeout(Method testMethod);

    /**

    • Determine if the supplied test method is annotated with @Timed.
    • @param testMethod the test method to check
    • @return true if the method is annotated with @Timed */ public static boolean isTimed(Method testMethod);

    /**

    • Determine if the supplied test method is annotated with @Repeat.
    • @param testMethod the test method to check
    • @return true if the method is annotated with @Repeat */ public static boolean isRepeated(Method testMethod); }

Install with Tessl CLI

npx tessl i tessl/maven-org-springframework--spring-test

docs

bean-override-framework.md

index.md

jdbc-testing.md

junit-integration.md

mock-objects.md

testcontext-framework.md

testing-annotations.md

web-testing.md

tile.json