CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Starter for testing Spring Boot applications with libraries including JUnit Jupiter, Hamcrest and Mockito

Pending
Overview
Eval results
Files

core-testing.mddocs/

Core Testing Framework

Core Spring Boot testing capabilities providing integration test support, context loading, and test configuration management.

Capabilities

@SpringBootTest Annotation

Main annotation for Spring Boot integration tests with full application context loading.

/**
 * Annotation for a Spring Boot test that loads the full application context
 * @since 1.4.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
public @interface SpringBootTest {
    /**
     * Properties in form key=value that should be added to the Spring Environment before the test runs
     */
    String[] properties() default {};
    
    /**
     * Application arguments that should be passed to the application under test
     */
    String[] args() default {};
    
    /**
     * The annotated classes to use for loading an ApplicationContext
     */
    Class<?>[] classes() default {};
    
    /**
     * The type of web environment to create when applicable
     */
    WebEnvironment webEnvironment() default WebEnvironment.MOCK;
    
    /**
     * Whether the application's main method should be called to start the context
     */
    UseMainMethod useMainMethod() default UseMainMethod.WHEN_AVAILABLE;
    
    /**
     * Web environment modes for SpringBootTest
     */
    enum WebEnvironment {
        /**
         * Loads a web ApplicationContext and provides a mock web environment
         */
        MOCK(false),
        
        /**
         * Loads a WebServerApplicationContext and provides a real web environment listening on a random port
         */
        RANDOM_PORT(true),
        
        /**
         * Loads a WebServerApplicationContext and provides a real web environment listening on a defined port
         */
        DEFINED_PORT(true),
        
        /**
         * Loads a regular ApplicationContext (no web environment)
         */
        NONE(false);
        
        private final boolean embedded;
        
        WebEnvironment(boolean embedded) {
            this.embedded = embedded;
        }
        
        public boolean isEmbedded() {
            return this.embedded;
        }
    }
    
    /**
     * Options for using the application's main method
     */
    enum UseMainMethod {
        /**
         * Always use the main method to start the context
         */
        YES,
        
        /**
         * Never use the main method to start the context  
         */
        NO,
        
        /**
         * Use the main method when available
         */
        WHEN_AVAILABLE
    }
}

Usage Examples:

// Basic integration test
@SpringBootTest
class BasicIntegrationTest {
    @Test
    void contextLoads() {
        // Test passes if context loads successfully
    }
}

// Test with web environment
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebIntegrationTest {
    @LocalServerPort
    int port;
    
    @Test
    void webContextLoads() {
        assertThat(port).isGreaterThan(0);
    }
}

// Test with custom properties
@SpringBootTest(properties = {
    "app.name=test-app",
    "debug=true"
})
class PropertyTest {
    @Value("${app.name}")
    String appName;
    
    @Test
    void propertyIsSet() {
        assertThat(appName).isEqualTo("test-app");
    }
}

@TestConfiguration Annotation

Annotation for test-specific configuration classes.

/**
 * Annotation for test configuration classes that should be included in tests
 * @since 1.4.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface TestConfiguration {
    /**
     * Explicitly specify the value for the associated bean definition
     */
    String value() default "";
    
    /**
     * Specify whether @Bean methods should get proxied in order to enforce bean lifecycle behavior
     */
    boolean proxyBeanMethods() default true;
}

Usage Examples:

@TestConfiguration
static class TestConfig {
    @Bean
    @Primary
    public UserService mockUserService() {
        return Mockito.mock(UserService.class);
    }
}

@SpringBootTest
@Import(TestConfig.class)
class ConfigurationTest {
    @Autowired
    UserService userService;
    
    @Test
    void usesTestConfiguration() {
        assertThat(userService).matches(Mockito::mockingDetails);
    }
}

Context Bootstrapping

Core classes for bootstrapping Spring Boot test contexts.

/**
 * TestContextBootstrapper for Spring Boot integration tests
 */
public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstrapper {
    /**
     * Process context configuration for SpringBootTest
     */
    @Override
    protected Class<?>[] getOrFindConfigurationClasses(MergedContextConfiguration mergedConfig);
    
    /**
     * Get context loader for Spring Boot tests
     */
    @Override
    protected Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass);
}

/**
 * ApplicationContextInitializer for Spring Boot tests
 */
public class ConfigDataApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    /**
     * Initialize the application context with config data support
     */
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext);
}

Port Injection Annotations

Annotations for injecting server ports in web integration tests.

/**
 * Annotation for injecting the HTTP port that got allocated at runtime
 * @since 1.4.0
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${local.server.port}")
public @interface LocalServerPort {
}

/**
 * Annotation for injecting the management port that got allocated at runtime
 * @since 1.4.0
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${local.management.port}")
public @interface LocalManagementPort {
}

/**
 * Annotation for injecting the RSocket server port that got allocated at runtime
 * @since 2.2.0
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Value("${local.rsocket.server.port}")
public @interface LocalRSocketServerPort {
}

Usage Examples:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PortInjectionTest {
    @LocalServerPort
    int serverPort;
    
    @LocalManagementPort  
    int managementPort;
    
    @Test
    void portsAreInjected() {
        assertThat(serverPort).isGreaterThan(0);
        assertThat(managementPort).isGreaterThan(0);
    }
}

Test Component Scanning

Component scanning configuration for test classes.

/**
 * Annotation for components that should only be picked up during component scanning in tests
 * @since 1.4.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface TestComponent {
    /**
     * The value for the associated bean definition
     */
    String value() default "";
}

Test Utilities

Utility classes for test setup and configuration.

/**
 * Utility methods for working with ApplicationContext in tests
 */
public class ApplicationContextTestUtils {
    /**
     * Close an ApplicationContext and ignore any exception
     */
    public static void closeQuietly(ApplicationContext context);
}

/**
 * Utility for adding properties to Environment in tests
 */
public class TestPropertyValues {    
    /**
     * Create TestPropertyValues from property strings
     */
    public static TestPropertyValues of(String... pairs);
    
    /**
     * Apply these properties to the given environment
     */
    public void applyTo(ConfigurableEnvironment environment);
    
    /**
     * Apply these properties to the given context
     */
    public void applyTo(ConfigurableApplicationContext context);
    
    /**
     * Apply these properties to the given application context runner
     */
    public void applyTo(ApplicationContextRunner runner);
}

Usage Examples:

class TestUtilitiesExample {
    @Test
    void addPropertiesToEnvironment() {
        ConfigurableEnvironment environment = new StandardEnvironment();
        
        TestPropertyValues.of("app.name=test", "debug=true")
            .applyTo(environment);
            
        assertThat(environment.getProperty("app.name")).isEqualTo("test");
        assertThat(environment.getProperty("debug")).isEqualTo("true");
    }
}

Common Exceptions and Error Handling

Test Context Failures

Common exceptions that may occur during Spring Boot test execution:

Key Exceptions:

  • BeanCreationException: Thrown when required beans cannot be instantiated
  • NoSuchBeanDefinitionException: Thrown when expected beans are not found
  • BeanDefinitionStoreException: Thrown when bean definitions are invalid
  • ApplicationContextException: General context loading failures

Error Handling Examples:

@SpringBootTest
class ErrorHandlingTest {
    
    @Test
    void handleContextLoadFailure() {
        // This test would fail if context cannot load
        // Common causes:
        // - Missing required beans
        // - Configuration conflicts  
        // - Invalid property values
        // - Classpath issues
    }
    
    @Test
    void handleMissingBeanError() {
        // Use @MockBean to provide missing dependencies
        // Or exclude problematic auto-configurations
        // Example: @SpringBootTest(exclude = {DataSourceAutoConfiguration.class})
    }
}

Common Error Scenarios

  1. Context Load Failures: Usually caused by missing dependencies or configuration conflicts
  2. Bean Creation Errors: Often due to missing required properties or constructor arguments
  3. Property Resolution Issues: Invalid property placeholders or missing configuration files
  4. Profile Activation Problems: Incorrect profile-specific configurations
  5. Test Slice Conflicts: Mixing incompatible test slice annotations

Install with Tessl CLI

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

docs

context-testing.md

core-testing.md

index.md

json-testing.md

mock-integration.md

output-capture.md

test-slices.md

web-testing.md

tile.json