Mock Objects
Spring includes a number of packages dedicated to mocking:
Environment
The org.springframework.mock.env
package contains mock implementations of the
Environment
and PropertySource
abstractions (see
Bean Definition Profiles
and PropertySource
Abstraction).
MockEnvironment
and MockPropertySource
are useful for developing
out-of-container tests for code that depends on environment-specific properties.
JNDI
The org.springframework.mock.jndi
package contains a partial implementation of the JNDI
SPI, which you can use to set up a simple JNDI environment for test suites or stand-alone
applications. If, for example, JDBC DataSource
instances get bound to the same JNDI
names in test code as they do in a Java EE container, you can reuse both application code
and configuration in testing scenarios without modification.
The mock JNDI support in the org.springframework.mock.jndi package is
officially deprecated as of Spring Framework 5.2 in favor of complete solutions from third
parties such as Simple-JNDI.
|
Servlet API
The org.springframework.mock.web
package contains a comprehensive set of Servlet API
mock objects that are useful for testing web contexts, controllers, and filters. These
mock objects are targeted at usage with Spring’s Web MVC framework and are generally more
convenient to use than dynamic mock objects (such as EasyMock)
or alternative Servlet API mock objects (such as MockObjects).
Since Spring Framework 5.0, the mock objects in org.springframework.mock.web are
based on the Servlet 4.0 API.
|
The Spring MVC Test framework builds on the mock Servlet API objects to provide an integration testing framework for Spring MVC. See spring-mvc-test-framework.
Spring Web Reactive
The org.springframework.mock.http.server.reactive
package contains mock implementations
of ServerHttpRequest
and ServerHttpResponse
for use in WebFlux applications. The
org.springframework.mock.web.server
package contains a mock ServerWebExchange
that
depends on those mock request and response objects.
Both MockServerHttpRequest
and MockServerHttpResponse
extend from the same abstract
base classes as server-specific implementations and share behavior with them. For
example, a mock request is immutable once created, but you can use the mutate()
method
from ServerHttpRequest
to create a modified instance.
In order for the mock response to properly implement the write contract and return a
write completion handle (that is, Mono<Void>
), it by default uses a Flux
with
cache().then()
, which buffers the data and makes it available for assertions in tests.
Applications can set a custom write function (for example, to test an infinite stream).
The webtestclient builds on the mock request and response to provide support for testing WebFlux applications without an HTTP server. The client can also be used for end-to-end tests with a running server.