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

mock-objects.mddocs/

Mock Objects

Spring Test provides comprehensive mock implementations of Servlet API, HTTP client, and reactive server components. These mock objects are essential for unit testing and integration testing without requiring actual server infrastructure.

Capabilities

Servlet API Mocks

Mock implementations of core Servlet API components for testing web applications.

/**
 * Mock implementation of the HttpServletRequest interface.
 */
public class MockHttpServletRequest implements HttpServletRequest {
    
    /**
     * Create a new MockHttpServletRequest.
     */
    public MockHttpServletRequest();
    
    /**
     * Create a new MockHttpServletRequest with the specified method and request URI.
     * @param method the request method (e.g., "GET", "POST")
     * @param requestURI the request URI
     */
    public MockHttpServletRequest(String method, String requestURI);
    
    /**
     * Create a new MockHttpServletRequest with the specified ServletContext.
     * @param servletContext the ServletContext
     */
    public MockHttpServletRequest(ServletContext servletContext);
    
    /**
     * Set the HTTP request method.
     * @param method the request method (e.g., "GET", "POST")
     */
    public void setMethod(String method);
    
    /**
     * Set the request URI.
     * @param requestURI the request URI
     */
    public void setRequestURI(String requestURI);
    
    /**
     * Set the servlet path.
     * @param servletPath the servlet path
     */
    public void setServletPath(String servletPath);
    
    /**
     * Set the path info.
     * @param pathInfo the path info
     */
    public void setPathInfo(String pathInfo);
    
    /**
     * Set the query string.
     * @param queryString the query string
     */
    public void setQueryString(String queryString);
    
    /**
     * Add a single value for the specified HTTP parameter.
     * @param name the parameter name
     * @param value the parameter value
     */
    public void addParameter(String name, String value);
    
    /**
     * Add multiple values for the specified HTTP parameter.
     * @param name the parameter name
     * @param values the parameter values
     */
    public void addParameter(String name, String... values);
    
    /**
     * Set all parameters from the given Map.
     * @param params the parameter map
     */
    public void setParameters(Map<String, String[]> params);
    
    /**
     * Add a header with the given name and value.
     * @param name the header name
     * @param value the header value
     */
    public void addHeader(String name, Object value);
    
    /**
     * Set the content of the request body.
     * @param content the content as a byte array
     */
    public void setContent(byte[] content);
    
    /**
     * Set the content type of the request.
     * @param contentType the content type
     */
    public void setContentType(String contentType);
    
    /**
     * Add cookies to the request.
     * @param cookies the cookies to add
     */
    public void setCookies(Cookie... cookies);
    
    /**
     * Set the character encoding of the request.
     * @param characterEncoding the character encoding
     */
    public void setCharacterEncoding(String characterEncoding);
    
    /**
     * Set the remote address of the client.
     * @param remoteAddr the remote address
     */
    public void setRemoteAddr(String remoteAddr);
    
    /**
     * Set the remote host of the client.
     * @param remoteHost the remote host
     */
    public void setRemoteHost(String remoteHost);
    
    /**
     * Set the remote port of the client.
     * @param remotePort the remote port
     */
    public void setRemotePort(int remotePort);
    
    /**
     * Set the local address of the server.
     * @param localAddr the local address
     */
    public void setLocalAddr(String localAddr);
    
    /**
     * Set the local name of the server.
     * @param localName the local name
     */
    public void setLocalName(String localName);
    
    /**
     * Set the local port of the server.
     * @param localPort the local port
     */
    public void setLocalPort(int localPort);
    
    /**
     * Set whether the request is secure (HTTPS).
     * @param secure true if the request is secure
     */
    public void setSecure(boolean secure);
    
    /**
     * Set the scheme of the request (http, https).
     * @param scheme the scheme
     */
    public void setScheme(String scheme);
    
    /**
     * Set the server name.
     * @param serverName the server name
     */
    public void setServerName(String serverName);
    
    /**
     * Set the server port.
     * @param serverPort the server port
     */
    public void setServerPort(int serverPort);
}

/**
 * Mock implementation of the HttpServletResponse interface.
 */
public class MockHttpServletResponse implements HttpServletResponse {
    
    /**
     * Create a new MockHttpServletResponse.
     */
    public MockHttpServletResponse();
    
    /**
     * Get the HTTP status code.
     * @return the status code
     */
    public int getStatus();
    
    /**
     * Set the HTTP status code.
     * @param status the status code
     */
    public void setStatus(int status);
    
    /**
     * Get the error message associated with the status code.
     * @return the error message (may be null)
     */
    @Nullable
    public String getErrorMessage();
    
    /**
     * Get the content of the response as a String.
     * @return the content as a String
     * @throws UnsupportedEncodingException if the character encoding is not supported
     */
    public String getContentAsString() throws UnsupportedEncodingException;
    
    /**
     * Get the content of the response as a String with the specified encoding.
     * @param charset the character set to use for decoding
     * @return the content as a String
     */
    public String getContentAsString(Charset charset);
    
    /**
     * Get the content of the response as a byte array.
     * @return the content as a byte array
     */
    public byte[] getContentAsByteArray();
    
    /**
     * Get the size of the response content in bytes.
     * @return the content size
     */
    public int getContentSize();
    
    /**
     * Get the value of the specified response header.
     * @param name the header name
     * @return the header value (may be null)
     */
    @Nullable
    public Object getHeader(String name);
    
    /**
     * Get all values for the specified response header.
     * @param name the header name
     * @return the list of header values (never null, but may be empty)
     */
    public List<Object> getHeaders(String name);
    
    /**
     * Get all response header names.
     * @return the collection of header names (never null)
     */
    public Collection<String> getHeaderNames();
    
    /**
     * Get all cookies that have been added to the response.
     * @return the array of cookies (never null)
     */
    public Cookie[] getCookies();
    
    /**
     * Get the cookie with the specified name.
     * @param name the cookie name
     * @return the cookie (may be null)
     */
    @Nullable
    public Cookie getCookie(String name);
    
    /**
     * Get the URL to which the response was redirected.
     * @return the redirect URL (may be null)
     */
    @Nullable
    public String getRedirectedUrl();
    
    /**
     * Get the URL to which the request was forwarded.
     * @return the forward URL (may be null)
     */
    @Nullable
    public String getForwardedUrl();
    
    /**
     * Get the included URLs.
     * @return the list of included URLs (never null)
     */
    public List<String> getIncludedUrls();
}

/**
 * Mock implementation of the ServletContext interface.
 */
public class MockServletContext implements ServletContext {
    
    /**
     * Create a new MockServletContext.
     */
    public MockServletContext();
    
    /**
     * Create a new MockServletContext with the specified resource base path.
     * @param resourceBasePath the base path for resources
     */
    public MockServletContext(String resourceBasePath);
    
    /**
     * Create a new MockServletContext with the specified ResourceLoader.
     * @param resourceLoader the ResourceLoader to use
     */
    public MockServletContext(ResourceLoader resourceLoader);
    
    /**
     * Add an initialization parameter.
     * @param name the parameter name
     * @param value the parameter value
     */
    public void addInitParameter(String name, String value);
    
    /**
     * Set a context attribute.
     * @param name the attribute name
     * @param value the attribute value
     */
    public void setAttribute(String name, Object value);
    
    /**
     * Set the context path.
     * @param contextPath the context path
     */
    public void setContextPath(String contextPath);
    
    /**
     * Add a MIME type mapping.
     * @param fileExtension the file extension (without the leading dot)
     * @param mimeType the MIME type
     */
    public void addMimeType(String fileExtension, String mimeType);
    
    /**
     * Set the server info string.
     * @param serverInfo the server info
     */
    public void setServerInfo(String serverInfo);
    
    /**
     * Set the major version number.
     * @param majorVersion the major version
     */
    public void setMajorVersion(int majorVersion);
    
    /**
     * Set the minor version number.
     * @param minorVersion the minor version
     */
    public void setMinorVersion(int minorVersion);
}

/**
 * Mock implementation of the HttpSession interface.
 */
public class MockHttpSession implements HttpSession {
    
    /**
     * Create a new MockHttpSession.
     */
    public MockHttpSession();
    
    /**
     * Create a new MockHttpSession with the specified ServletContext.
     * @param servletContext the ServletContext
     */
    public MockHttpSession(ServletContext servletContext);
    
    /**
     * Create a new MockHttpSession with the specified ServletContext and session ID.
     * @param servletContext the ServletContext
     * @param id the session ID
     */
    public MockHttpSession(ServletContext servletContext, String id);
    
    /**
     * Set a session attribute.
     * @param name the attribute name
     * @param value the attribute value
     */
    public void setAttribute(String name, Object value);
    
    /**
     * Get a session attribute.
     * @param name the attribute name
     * @return the attribute value (may be null)
     */
    @Nullable
    public Object getAttribute(String name);
    
    /**
     * Remove a session attribute.
     * @param name the attribute name
     */
    public void removeAttribute(String name);
    
    /**
     * Clear all session attributes.
     */
    public void clearAttributes();
    
    /**
     * Set the maximum inactive interval for this session.
     * @param interval the maximum inactive interval in seconds
     */
    public void setMaxInactiveInterval(int interval);
    
    /**
     * Mark this session as invalid.
     */
    public void invalidate();
    
    /**
     * Determine whether this session is new.
     * @return true if the session is new
     */
    public boolean isNew();
    
    /**
     * Set whether this session is new.
     * @param value true if the session should be marked as new
     */
    public void setNew(boolean value);
}

HTTP Client Mocks

Mock implementations for HTTP client testing.

/**
 * Mock implementation of ClientHttpRequest for testing HTTP clients.
 */
public class MockClientHttpRequest extends AbstractClientHttpRequest {
    
    /**
     * Create a new MockClientHttpRequest.
     * @param httpMethod the HTTP method
     * @param uri the URI
     */
    public MockClientHttpRequest(HttpMethod httpMethod, URI uri);
    
    /**
     * Set the HTTP method.
     * @param httpMethod the HTTP method
     */
    public void setMethod(HttpMethod httpMethod);
    
    /**
     * Get the HTTP method.
     * @return the HTTP method
     */
    public HttpMethod getMethod();
    
    /**
     * Get the URI.
     * @return the URI
     */
    public URI getURI();
    
    /**
     * Get the request headers.
     * @return the HttpHeaders instance
     */
    public HttpHeaders getHeaders();
    
    /**
     * Get the request body as a byte array.
     * @return the body as a byte array
     */
    public byte[] getBodyAsBytes();
    
    /**
     * Get the request body as a String.
     * @return the body as a String
     */
    public String getBodyAsString();
    
    /**
     * Get the request body as a String with the specified charset.
     * @param charset the character set to use
     * @return the body as a String
     */
    public String getBodyAsString(Charset charset);
    
    /**
     * Set the response to return when this request is executed.
     * @param clientHttpResponse the mock response
     */
    public void setResponse(MockClientHttpResponse clientHttpResponse);
}

/**
 * Mock implementation of ClientHttpResponse for testing HTTP clients.
 */
public class MockClientHttpResponse implements ClientHttpResponse {
    
    /**
     * Create a new MockClientHttpResponse.
     * @param statusCode the HTTP status code
     */
    public MockClientHttpResponse(HttpStatusCode statusCode);
    
    /**
     * Create a new MockClientHttpResponse with body content.
     * @param body the response body
     * @param statusCode the HTTP status code
     */
    public MockClientHttpResponse(byte[] body, HttpStatusCode statusCode);
    
    /**
     * Set the HTTP status code.
     * @param statusCode the status code
     */
    public void setStatusCode(HttpStatusCode statusCode);
    
    /**
     * Get the HTTP status code.
     * @return the status code
     */
    public HttpStatusCode getStatusCode();
    
    /**
     * Set the status text.
     * @param statusText the status text
     */
    public void setStatusText(String statusText);
    
    /**
     * Get the status text.
     * @return the status text
     */
    public String getStatusText();
    
    /**
     * Get the response headers.
     * @return the HttpHeaders instance
     */
    public HttpHeaders getHeaders();
    
    /**
     * Get the response body as an InputStream.
     * @return the body as an InputStream
     */
    public InputStream getBody();
    
    /**
     * Set the response body.
     * @param body the body content
     */
    public void setBody(String body);
    
    /**
     * Set the response body as a byte array.
     * @param body the body content
     */
    public void setBody(byte[] body);
    
    /**
     * Set the response body from an InputStream.
     * @param body the body content
     */
    public void setBody(InputStream body);
}

Reactive Mocks

Mock implementations for reactive web testing.

/**
 * Mock implementation of ServerHttpRequest for reactive web testing.
 */
public class MockServerHttpRequest implements ServerHttpRequest {
    
    /**
     * Create a MockServerHttpRequest with GET method and root path.
     * @return the builder for further configuration
     */
    public static BaseBuilder<?> get();
    
    /**
     * Create a MockServerHttpRequest with POST method and root path.
     * @return the builder for further configuration
     */
    public static BodyBuilder post();
    
    /**
     * Create a MockServerHttpRequest with PUT method and root path.
     * @return the builder for further configuration
     */
    public static BodyBuilder put();
    
    /**
     * Create a MockServerHttpRequest with PATCH method and root path.
     * @return the builder for further configuration
     */
    public static BodyBuilder patch();
    
    /**
     * Create a MockServerHttpRequest with DELETE method and root path.
     * @return the builder for further configuration
     */
    public static BaseBuilder<?> delete();
    
    /**
     * Create a MockServerHttpRequest with HEAD method and root path.
     * @return the builder for further configuration
     */
    public static BaseBuilder<?> head();
    
    /**
     * Create a MockServerHttpRequest with OPTIONS method and root path.
     * @return the builder for further configuration
     */
    public static BaseBuilder<?> options();
    
    /**
     * Create a MockServerHttpRequest with the specified method and URI.
     * @param method the HTTP method
     * @param uri the URI
     * @return the builder for further configuration
     */
    public static BaseBuilder<?> method(HttpMethod method, URI uri);
    
    /**
     * Builder interface for MockServerHttpRequest.
     */
    public interface BaseBuilder<B extends BaseBuilder<B>> {
        
        /**
         * Set the URI for the request.
         * @param uri the URI
         * @return this builder
         */
        B uri(URI uri);
        
        /**
         * Add a header to the request.
         * @param name the header name
         * @param values the header values
         * @return this builder
         */
        B header(String name, String... values);
        
        /**
         * Add headers to the request.
         * @param headers the headers to add
         * @return this builder
         */
        B headers(MultiValueMap<String, String> headers);
        
        /**
         * Set a cookie on the request.
         * @param name the cookie name
         * @param value the cookie value
         * @return this builder
         */
        B cookie(String name, String value);
        
        /**
         * Add cookies to the request.
         * @param cookies the cookies to add
         * @return this builder
         */
        B cookies(MultiValueMap<String, String> cookies);
        
        /**
         * Set the remote address.
         * @param remoteAddress the remote address
         * @return this builder
         */
        B remoteAddress(InetSocketAddress remoteAddress);
        
        /**
         * Build the MockServerHttpRequest.
         * @return the built request
         */
        MockServerHttpRequest build();
    }
    
    /**
     * Builder for requests with body content.
     */
    public interface BodyBuilder extends BaseBuilder<BodyBuilder> {
        
        /**
         * Set the content type.
         * @param contentType the content type
         * @return this builder
         */
        BodyBuilder contentType(MediaType contentType);
        
        /**
         * Set the content length.
         * @param contentLength the content length
         * @return this builder
         */
        BodyBuilder contentLength(long contentLength);
        
        /**
         * Set the request body.
         * @param body the body content
         * @return this builder
         */
        BodyBuilder body(String body);
        
        /**
         * Set the request body as a byte array.
         * @param body the body content
         * @return this builder
         */
        BodyBuilder body(byte[] body);
        
        /**
         * Set the request body as a Flux.
         * @param body the body content
         * @return this builder
         */
        BodyBuilder body(Flux<DataBuffer> body);
    }
}

/**
 * Mock implementation of ServerHttpResponse for reactive web testing.
 */
public class MockServerHttpResponse implements ServerHttpResponse {
    
    /**
     * Create a new MockServerHttpResponse.
     */
    public MockServerHttpResponse();
    
    /**
     * Create a new MockServerHttpResponse with the specified DataBufferFactory.
     * @param dataBufferFactory the DataBufferFactory to use
     */
    public MockServerHttpResponse(DataBufferFactory dataBufferFactory);
    
    /**
     * Set the HTTP status code.
     * @param statusCode the status code
     */
    public void setStatusCode(HttpStatusCode statusCode);
    
    /**
     * Get the HTTP status code.
     * @return the status code (may be null)
     */
    @Nullable
    public HttpStatusCode getStatusCode();
    
    /**
     * Get the response headers.
     * @return the HttpHeaders instance
     */
    public HttpHeaders getHeaders();
    
    /**
     * Get the response cookies.
     * @return the MultiValueMap of cookies
     */
    public MultiValueMap<String, ResponseCookie> getCookies();
    
    /**
     * Write the given body to the response.
     * @param body the body to write
     * @return a Mono that completes when the body has been written
     */
    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body);
    
    /**
     * Write the response and complete.
     * @return a Mono that completes when the response has been written
     */
    public Mono<Void> setComplete();
    
    /**
     * Get the body that was written to this response as a Flux.
     * @return the response body
     */
    public Flux<DataBuffer> getBody();
    
    /**
     * Get the body that was written to this response as a String.
     * @return the response body as a String
     */
    public String getBodyAsString();
    
    /**
     * Get the body that was written to this response as a String with the specified charset.
     * @param charset the character set to use
     * @return the response body as a String
     */
    public String getBodyAsString(Charset charset);
}

Usage Examples:

import org.springframework.mock.web.*;
import org.springframework.mock.http.client.*;

// Servlet API mock usage
@Test
void testWithMockRequest() {
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "/users");
    request.setContentType(MediaType.APPLICATION_JSON_VALUE);
    request.setContent("{\"name\":\"John\"}".getBytes());
    request.addHeader("Authorization", "Bearer token123");
    request.addParameter("debug", "true");
    
    MockHttpServletResponse response = new MockHttpServletResponse();
    
    // Use with your servlet or controller
    myController.handleRequest(request, response);
    
    // Assert response
    assertThat(response.getStatus()).isEqualTo(201);
    assertThat(response.getContentAsString()).contains("\"id\":");
    assertThat(response.getHeader("Location")).isNotNull();
}

// Mock session usage
@Test
void testWithMockSession() {
    MockHttpSession session = new MockHttpSession();
    session.setAttribute("userId", 123L);
    session.setMaxInactiveInterval(3600);
    
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(session);
    
    // Test session-dependent functionality
    Object userId = request.getSession().getAttribute("userId");
    assertThat(userId).isEqualTo(123L);
}

// HTTP client mock usage  
@Test
void testHttpClientWithMocks() {
    MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/api/data"));
    MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK.value());
    response.setBody("{\"message\":\"success\"}");
    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    
    request.setResponse(response);
    
    // Use with RestTemplate or WebClient mocking
    ClientHttpResponse actualResponse = request.execute();
    assertThat(actualResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
}

// Reactive mock usage
@Test
void testReactiveWithMocks() {
    MockServerHttpRequest request = MockServerHttpRequest
        .post("/api/users")
        .contentType(MediaType.APPLICATION_JSON)
        .body("{\"name\":\"Jane\"}")
        .header("Authorization", "Bearer token")
        .build();
        
    MockServerHttpResponse response = new MockServerHttpResponse();
    
    // Use with reactive handlers
    ServerRequest serverRequest = ServerRequest.create(exchange(request, response), messageReaders);
    Mono<ServerResponse> result = userHandler.create(serverRequest);
    
    // Verify response
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
}

Types

/**
 * Mock implementation of Cookie for testing.
 */
public class MockCookie extends Cookie {
    
    /**
     * Create a MockCookie with the specified name and value.
     * @param name the cookie name
     * @param value the cookie value
     */
    public MockCookie(String name, String value);
    
    /**
     * Set the cookie comment.
     * @param comment the comment
     */
    public void setComment(String comment);
    
    /**
     * Set the cookie domain.
     * @param domain the domain
     */
    public void setDomain(String domain);
    
    /**
     * Set the maximum age of the cookie.
     * @param maxAge the maximum age in seconds
     */
    public void setMaxAge(int maxAge);
    
    /**
     * Set the cookie path.
     * @param path the path
     */
    public void setPath(String path);
    
    /**
     * Set whether the cookie should only be sent over secure connections.
     * @param secure true if the cookie is secure
     */
    public void setSecure(boolean secure);
    
    /**
     * Set the cookie version.
     * @param version the version
     */
    public void setVersion(int version);
    
    /**
     * Set whether the cookie is HTTP-only.
     * @param httpOnly true if the cookie is HTTP-only
     */
    public void setHttpOnly(boolean httpOnly);
}

/**
 * Mock implementation of Part for multipart request testing.
 */
public class MockPart implements Part {
    
    /**
     * Create a MockPart with the specified name and content.
     * @param name the part name
     * @param content the part content
     */
    public MockPart(String name, byte[] content);
    
    /**
     * Create a MockPart with the specified name and filename.
     * @param name the part name
     * @param filename the original filename
     * @param content the part content
     */
    public MockPart(String name, @Nullable String filename, byte[] content);
    
    /**
     * Get the name of this part.
     * @return the part name
     */
    public String getName();
    
    /**
     * Get the original filename.
     * @return the filename (may be null)
     */
    @Nullable
    public String getSubmittedFileName();
    
    /**
     * Get the content type of this part.
     * @return the content type (may be null)
     */
    @Nullable
    public String getContentType();
    
    /**
     * Get the size of this part in bytes.
     * @return the part size
     */
    public long getSize();
    
    /**
     * Get the content of this part as an InputStream.
     * @return the content as an InputStream
     * @throws IOException if an I/O error occurs
     */
    public InputStream getInputStream() throws IOException;
    
    /**
     * Get a header value by name.
     * @param name the header name
     * @return the header value (may be null)
     */
    @Nullable
    public String getHeader(String name);
    
    /**
     * Get all header values for the specified name.
     * @param name the header name
     * @return the collection of header values (never null)
     */
    public Collection<String> getHeaders(String name);
    
    /**
     * Get all header names.
     * @return the collection of header names (never null)
     */
    public Collection<String> getHeaderNames();
}

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