or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

bean-override-framework.mdindex.mdjdbc-testing.mdjunit-integration.mdmock-objects.mdtestcontext-framework.mdtesting-annotations.mdweb-testing.md
tile.json

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

Spring TestContext Framework for comprehensive integration testing of Spring applications

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

To install, run

npx @tessl/cli install tessl/maven-org-springframework--spring-test@6.2.0

index.mddocs/

Spring Test

Spring Test is the comprehensive testing framework for Spring applications, providing the TestContext Framework for integration testing, MockMvc for web layer testing, extensive mock objects, and seamless JUnit/TestNG integration. It enables developers to write robust tests with full dependency injection support and transaction management.

Package Information

  • Package Name: org.springframework:spring-test
  • Package Type: maven
  • Language: Java
  • Installation: <dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>6.2.8</version></dependency>

Core Imports

import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextManager;

For specific testing frameworks:

// JUnit Jupiter
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

// MockMvc testing
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

Basic Usage

import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.jupiter.api.Test;

@SpringJUnitConfig(AppConfig.class)
class UserServiceIntegrationTest {
    
    @Autowired
    private UserService userService;
    
    @Test
    void shouldCreateUser() {
        User user = new User("John", "john@example.com");
        User savedUser = userService.save(user);
        assertThat(savedUser.getId()).isNotNull();
    }
}

Web testing example:

import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.context.junit.jupiter.SpringJUnitWebConfig;

@SpringJUnitWebConfig(WebConfig.class)
class UserControllerTest {
    
    @Autowired
    private MockMvc mockMvc;
    
    @Test
    void shouldReturnUser() throws Exception {
        mockMvc.perform(get("/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("John"));
    }
}

Architecture

Spring Test is built around several key architectural components:

  • TestContext Framework: Core framework providing ApplicationContext loading, dependency injection, and transaction management for tests
  • TestContextBootstrapper: Bootstrap mechanism that configures the TestContext Framework based on annotations and conventions
  • TestExecutionListener: Event-driven lifecycle hooks for test execution (before/after class, method, execution)
  • ContextLoader: Strategy interface for loading ApplicationContext instances with various implementations for different configuration types
  • Mock Objects: Comprehensive mock implementations of Servlet API, HTTP client, and reactive components
  • Bean Override Framework: Modern replacement for @MockBean providing flexible bean substitution in tests
  • Integration Layer: Seamless integration with JUnit Jupiter, JUnit 4, and TestNG testing frameworks

Capabilities

TestContext Framework

Core testing framework providing ApplicationContext management, dependency injection, and transaction support for integration tests.

public interface TestContext {
    ApplicationContext getApplicationContext();
    boolean hasApplicationContext();
    Class<?> getTestClass();
    Object getTestInstance();
    Method getTestMethod();
    Throwable getTestException();
    void markApplicationContextDirty();
    void publishEvent(ApplicationEvent event);
}

public class TestContextManager {
    public TestContextManager(Class<?> testClass);
    public void beforeTestClass() throws Exception;
    public void prepareTestInstance(Object testInstance) throws Exception;
    public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception;
    public void beforeTestExecution(Object testInstance, Method testMethod) throws Exception;
    public void afterTestExecution(Object testInstance, Method testMethod, Throwable exception) throws Exception;
    public void afterTestMethod(Object testInstance, Method testMethod, Throwable exception) throws Exception;
    public void afterTestClass() throws Exception;
}

TestContext Framework

Web Testing Support

MockMvc framework for testing Spring MVC controllers without starting a full HTTP server, with fluent API for request building and response assertions.

public class MockMvc {
    public ResultActions perform(RequestBuilder requestBuilder) throws Exception;
}

public class MockMvcBuilders {
    public static DefaultMockMvcBuilder webAppContextSetup(WebApplicationContext context);
    public static StandaloneMockMvcBuilder standaloneSetup(Object... controllers);
}

public interface ResultActions {
    ResultActions andExpect(ResultMatcher matcher) throws Exception;
    ResultActions andExpectAll(ResultMatcher... matchers) throws Exception;
    ResultActions andDo(ResultHandler handler) throws Exception;
    MvcResult andReturn();
}

Web Testing

Mock Objects

Comprehensive mock implementations of Servlet API, HTTP client, and reactive server components for unit and integration testing.

public class MockHttpServletRequest implements HttpServletRequest {
    public void setMethod(String method);
    public void setRequestURI(String requestURI);
    public void addParameter(String name, String... values);
    public void addHeader(String name, Object value);
    public void setContent(byte[] content);
}

public class MockHttpServletResponse implements HttpServletResponse {
    public int getStatus();
    public String getContentAsString();
    public byte[] getContentAsByteArray();
    public String getHeader(String name);
    public String getRedirectedUrl();
}

Mock Objects

Testing Annotations

Core annotations for configuring test behavior, context loading, and transaction management in Spring tests.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContextConfiguration {
    String[] value() default {};
    String[] locations() default {};
    Class<?>[] classes() default {};
    Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
    boolean inheritLocations() default true;
    boolean inheritInitializers() default true;
    Class<? extends ContextLoader> loader() default ContextLoader.class;
}

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ActiveProfiles {
    String[] value() default {};
    String[] profiles() default {};
    Class<? extends ActiveProfilesResolver> resolver() default ActiveProfilesResolver.class;
    boolean inheritProfiles() default true;
}

Testing Annotations

JDBC Testing Support

Database testing utilities including SQL script execution and JDBC test utilities for data-driven testing scenarios.

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Sql {
    String[] value() default {};
    String[] scripts() default {};
    String[] statements() default {};
    ExecutionPhase executionPhase() default ExecutionPhase.BEFORE_TEST_METHOD;
    SqlConfig config() default @SqlConfig;
}

public class JdbcTestUtils {
    public static int countRowsInTable(JdbcTemplate jdbcTemplate, String tableName);
    public static int countRowsInTableWhere(JdbcTemplate jdbcTemplate, String tableName, String whereClause);
    public static int deleteFromTables(JdbcTemplate jdbcTemplate, String... tableNames);
    public static void executeSqlScript(JdbcTemplate jdbcTemplate, Resource resource, boolean continueOnError);
}

JDBC Testing

JUnit Integration

Seamless integration with JUnit Jupiter providing Spring-specific extensions and composite annotations for simplified test configuration.

public class SpringExtension implements BeforeAllCallback, AfterAllCallback, 
    TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, 
    BeforeTestExecutionCallback, AfterTestExecutionCallback, ParameterResolver {
}

@ExtendWith(SpringExtension.class)
@ContextConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SpringJUnitConfig {
    Class<?>[] value() default {};
    Class<?>[] classes() default {};
    String[] locations() default {};
    Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
}

@SpringJUnitConfig
@WebAppConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SpringJUnitWebConfig {
    Class<?>[] value() default {};
    Class<?>[] classes() default {};
    String[] locations() default {};
}

JUnit Integration

Bean Override Framework

Modern framework for overriding beans in Spring tests, providing unified alternatives to @MockBean with better performance and integration.

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MockitoBean {
    String value() default "";
    String name() default "";
    Class<?>[] types() default {};
    String contextName() default "";
    Class<?>[] extraInterfaces() default {};
    Answers answers() default Answers.RETURNS_DEFAULTS;
    boolean serializable() default false;
    MockReset reset() default MockReset.AFTER;
    boolean enforceOverride() default false;
}

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MockitoSpyBean {
    String value() default "";
    String name() default "";
    Class<?>[] types() default {};
    String contextName() default "";
    MockReset reset() default MockReset.AFTER;
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestBean {
    String value() default "";
    String name() default "";
    String methodName() default "";
    String contextName() default "";
    boolean enforceOverride() default false;
}

public enum MockReset {
    BEFORE, AFTER, NONE
}

Bean Override Framework

Types

public interface TestExecutionListener {
    default void beforeTestClass(TestContext testContext) throws Exception {}
    default void prepareTestInstance(TestContext testContext) throws Exception {}
    default void beforeTestMethod(TestContext testContext) throws Exception {}
    default void beforeTestExecution(TestContext testContext) throws Exception {}
    default void afterTestExecution(TestContext testContext) throws Exception {}
    default void afterTestMethod(TestContext testContext) throws Exception {}
    default void afterTestClass(TestContext testContext) throws Exception {}
}

public interface ContextLoader {
    String[] processLocations(Class<?> clazz, String... locations);
    ApplicationContext loadContext(String... locations) throws Exception;
}

public interface SmartContextLoader extends ContextLoader {
    ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception;
    void processContextConfiguration(ContextConfigurationAttributes configAttributes);
}

public enum DirtiesContext.ClassMode {
    BEFORE_CLASS,
    BEFORE_EACH_TEST_METHOD,
    AFTER_EACH_TEST_METHOD,
    AFTER_CLASS
}

public enum DirtiesContext.MethodMode {
    BEFORE_METHOD,
    AFTER_METHOD
}

public enum Sql.ExecutionPhase {
    BEFORE_TEST_METHOD,
    AFTER_TEST_METHOD,
    BEFORE_TEST_CLASS,
    AFTER_TEST_CLASS
}

/**
 * Strategy interface for invoking test methods.
 */
@FunctionalInterface
public interface MethodInvoker {
    
    /**
     * Default MethodInvoker implementation that uses reflection.
     */
    MethodInvoker DEFAULT_INVOKER = (testInstance, method, args) -> {
        return method.invoke(testInstance, args);
    };
    
    /**
     * Invoke the supplied test method on the supplied test instance with the supplied arguments.
     * @param testInstance the test instance on which to invoke the method
     * @param method the method to invoke
     * @param args the arguments to pass to the method
     * @return the value returned by the method invocation
     * @throws Exception if method invocation fails
     */
    Object invoke(Object testInstance, Method method, Object... args) throws Exception;
}