Prior to this change, calling the `setDateHeader` method on a
Spring Test MockHttpServletResponse instance would just store the given
long value in a Map, not writing it as a formatted date String.
Also, calling `getDateHeader` on a MockHttpServletRequest would not
support date strings and could not parse those values.
This can be problematic when testing features related to date headers
such as "Expires", "If-Modified-Since", "Last-Modified", etc.
This commit adds formatting and parsing capabilities to Servlet Mocks
for date strings in HTTP headers.
When formatting dates to Strings, the date format used is the one
preferred by the HTTP RFC. When parsing date Strings, multiple date
formats are supported for better compatibility.
Issue: SPR-11912
SPR-13211 introduced support for reusing mock requests in Spring MVC
Test if the request was created by the the Spring TestContext
Framework. Unfortunately, that change makes it impossible for
MockMvc.perform() to be invoked multiple times within the same test
method without side effects. For example, session attributes and
request parameters are transparently and unexpectedly retained for
subsequent invocations of perform(), causing certain categories of
tests to fail.
This commit reverts the changes introduced in SPR-13211 and introduces
a new MockMvcReuseTests class to serve as regression tests within
Spring's test suite.
Issue: SPR-13260, SPR-13211
HTTP headers such as "Expires", "Last-Modified" all use date
strings like "Tue, 21 Jul 2015 10:00:00 GMT". Prior to this commit,
there was no way to match those header values, besides formatting dates
manually.
This commit introduces a new HeaderResultMatcher to test those date
headers using a long timestamp:
```
this.mockMvc.perform(get("/persons/1").header("If-Modified-Since", now))
.andExpect(status().isNotModified())
.andExpect(header().dateValue("Last-Modified", timestamp));
```
Issue: SPR-13263
Prior to this commit, the Spring MVC Test Framework always created a
new MockHttpServletRequest, disregarding any mock request already
present in Spring Web's RequestContextHolder -- for example, one
created by the ServletTestExecutionListener in the Spring TestContext
Framework (TCF).
This commit modifies MockHttpServletRequestBuilder so that it reuses a
mock request created by the TCF. However,
MockMultipartHttpServletRequestBuilder continues to always create a new
MockMultipartHttpServletRequest since a MockHttpServletRequest created
by the TCF is not directly compatible with a
MockMultipartHttpServletRequest. Furthermore, in order to avoid
unforeseen side effects, MockHttpServletRequestBuilder will always
create a new MockHttpServletRequest if a mock request is present in the
RequestContextHolder but not created by the TCF.
Issue: SPR-13211
When using the Spring TestContext Framework (TCF) to load a
WebApplicationContext and the Spring MVC Test Framework (MockMvc) to
test a controller, two instances of MockHttpServletRequest will be
created. Due to an ordering issue with regard to population of the
RequestAttributes, it is therefore possible that a filter accesses the
mocked request managed by the TCF, while the controller accesses the
mocked request managed by MockMvc, and this leads to test failures if
the controller expects data from the filter to be present in the
request.
This commit fixes this bug by ensuring that the RequestAttributes
backed by the mocked request managed by MockMvc are stored in the
RequestContextHolder before any filters are invoked by MockMvc.
Issue: SPR-13217
This commit adds additional tests to RequestContextHolderTests that
verify proper support for the MockHttpServletRequest managed by Spring
MVC Test in the following scenarios:
- request-scoped service invoked by controller
- session-scoped service invoked by controller
- custom filter that sets request attributes
Issue: SPR-13211
SPR-12429 introduced various `BEFORE_*` modes in `@DirtiesContext`. To
support these new modes, `DirtiesContextTestExecutionListener` (DCTEL)
was updated to support both `BEFORE_*` and `AFTER_*` modes. However,
there is a problem with having DCTEL support `BEFORE_*` modes since it
is typically configured to execute after the
`DependencyInjectionTestExecutionListener` (DITEL), and this leads to
several undesired side effects:
- The test's `ApplicationContext` is closed by DCTEL *after*
dependencies have been injected into the test instance.
- Injected dependencies may therefore attempt to interact with an
`ApplicationContext` that is no longer _active_.
- If a test has its `ApplicationContext` injected as a dependency,
interaction with the context will likely fail since the context has
been closed.
- Any `TestExecutionListeners` registered after DCTEL will get a _new_
`ApplicationContext` if they invoke `getApplicationContext()` on the
`TestContext`.
This commit fixes these issues by introducing a new
`DirtiesContextBeforeModesTestExecutionListener` (DCBMTEL) that is
registered by default before DITEL. The previous support for `BEFORE_*`
modes has been moved from DCTEL to DCBMTEL. In addition, an
`AbstractDirtiesContextTestExecutionListener` has been extracted from
DCTEL in order to avoid code duplication.
Issue: SPR-13180
Prior to this commit, the Spring MVC Test framework only provided
support for printing debug information about the MvcResult to STDOUT.
This commit introduces support for logging `MvcResult` details at
`DEBUG` level via the Apache Commons Logging API. In addition, this
commit introduces additional `print(..)` variants for printing debug
information to custom output streams and writers.
Specifically, `MockMvcResultHandlers` has been augmented with the
following new static methods:
- `log()`
- `print(OutputStream)`
- `print(Writer)`
Issue: SPR-13171
Prior to this commit, when rendering cookies via `andDo(print())` in
Spring MVC Test, the output for the `MockHttpServletResponse` would
look something like the following:
Cookies = [javax.servlet.http.Cookie@25084a1e]
The reason is that the Cookie class in javax.servlet-api-3.0.1.jar does
not implement toString(). Consequently, nothing about the cookie's
name, value, etc., is displayed, thereby making the debug output for
cookies next to useless.
This commit improves on this by implementing custom toString() logic
for cookies in debug output in Spring MVC Test. For example, the output
now looks like this (without the newlines):
Cookies = [[Cookie@47faa49c name = 'enigma', value = '42', \\
comment = [null], domain = [null], maxAge = -1, \\
path = [null], secure = false, version = 0, \\
httpOnly = false]]
In addition, this commit fixes a minor bug for FlashMap debug output if
the FlashMap is empty.
Issue: SPR-13168
Prior to this commit, it was only possible to declare SQL statements
via @Sql within external script resources (i.e., classpath or file
system resources); however, many developers have inquired about the
ability to inline SQL statements with @Sql analogous to the support for
inlined properties in @TestPropertySource.
This commit introduces support for declaring _inlined SQL statements_
in `@Sql` via a new `statements` attribute. Inlined statements are
executed after statements in scripts.
Issue: SPR-13159
This commit introduces a convenience method in AnnotationUtils for
synthesizing an annotation from its default attribute values.
TransactionalTestExecutionListener has been refactored to invoke this
new convenience method.
Issue: SPR-13087
Prior to this commit, the implementation of getRepeatableAnnotation()
in Spring's AnnotationUtils complied neither with the contract of
getAnnotationsByType() nor with the contract of
getDeclaredAnnotationsByType() as defined in AnnotatedElement in Java 8.
Specifically, unexpected results can be encountered when using Spring's
support for @Repeatable annotations: either annotations show up in the
returned set in the wrong order, or annotations are returned in the set
that should not even be found based on the semantics of @Repeatable.
This commit remedies this problem by deprecating the existing
getRepeatableAnnotation() methods and replacing them with new
getRepeatableAnnotations() and getDeclaredRepeatableAnnotations()
methods that comply with the contracts of Java's getAnnotationsByType()
and getDeclaredAnnotationsByType(), respectively.
Issue: SPR-13068
The initial support for synthesizing an annotation from a Map (or
AnnotationAttributes) introduced in SPR-13067 required that the map
contain key-value pairs for every attribute defined by the supplied
annotationType. However, there are use cases that would benefit from
being able to supply a reduced set of attributes and still have the
annotation synthesized properly.
This commit refines the validation mechanism in
MapAnnotationAttributeExtractor so that a reduced set of attributes may
be supplied. Specifically, if an attribute is missing in the supplied
map the attribute will be set either to value of its alias (if an alias
value configured via @AliasFor exists) or to the value of the
attribute's default value (if defined), and otherwise an exception will
be thrown.
Furthermore, TransactionalTestExecutionListener has been refactored to
take advantage of this new feature by synthesizing an instance of
@TransactionConfiguration solely from the default values of its
declared attributes.
Issue: SPR-13087
Prior to this change, `XpathResultMatchers` and more generally the
`MockHttpServletResponse` would default to ISO-8859-1 encoding even when
it's not supposed to. The Servlet/HTTP specs mention this encoding
for all `text/*` mime types when decoding bodies to Strings, but this
issue is about XML Parsers.
XML Parsers should use the encoding:
* defined in the `Content-Type` response header (if available)
* written in the XML declaration of the document
* "guessed" by a built-in auto-detection mechanism
This commit changes the following:
* XPathMatchers now feed the XML parser with byte arrays instead of
decoded Strings
* the response should be written to `MockHttpServletResponse` using
its OutputStream, and not a PrintWriter which defaults to ISO-8859-1
Issue: SPR-12676
Ever since @ActiveProfiles was introduced, the declared active profiles
for integration tests have been sorted in order to support unique cache
key generation; however, there are use cases for which the original
ordering should be retained.
For example, Spring Boot's ConfigFileApplicationListener loads
configuration files for active profiles in the order returned by
Environment.getActiveProfiles(), with the assumption that the ordering
matches the order in which the developer declared the active profiles.
This commit maintains the uniqueness of active profiles declared via
@ActiveProfiles but no longer sorts them.
Issue: SPR-12492
In AnnotatedElementUtils, all methods pertaining to merging annotation
attributes have been renamed to "getMerged*()" and "findMerged*()"
accordingly. Existing methods such as getAnnotationAttributes(..) have
been deprecated in favor of the more descriptive "merged" variants.
This aligns the naming conventions in AnnotatedElementUtils with those
already present in AnnotationReadingVisitorUtils.
The use of "annotationType" as a variable name for the fully qualified
class name of an annotation type has been replaced with
"annotationName" in order to improve the readability and intent of the
code base.
In MetaAnnotationUtils.AnnotationDescriptor, getMergedAnnotation() has
been renamed to synthesizeAnnotation(), and the method is now
overridden in UntypedAnnotationDescriptor to always throw an
UnsupportedOperationException in order to avoid potential run-time
ClassCastExceptions.
Issue: SPR-11511
The modifications to DefaultMockMvcBuilder performed in conjunction
with SPR-12553 introduced a breaking change: the WebApplicationContext
supplied to DefaultMockMvcBuilder's constructor was *always* stored in
the ServletContext as the root WebApplicationContext, overwriting a
root WebApplicationContext that had been set by the user or by the
Spring TestContext Framework (TCF) -- for example, in
AbstractGenericWebContextLoader. Consequently, the changes in SPR-12553
cause tests that use @ContextHierarchy to fail if web components rely
on the correct WebApplicationContext being stored under the
WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE key.
This commit reverts the breaking changes introduced in SPR-12553: if
the root WebApplicationContext has already been set in the
ServletContext of the WebApplicationContext supplied to
DefaultMockMvcBuilder, no action is taken.
Furthermore, this commit introduces new code to address the initial
intent of SPR-12553. Specifically, if the root WebApplicationContext
has NOT been set in the ServletContext of the WebApplicationContext
supplied to DefaultMockMvcBuilder, the application context hierarchy
will be traversed in search of the root WebApplicationContext, and the
root WebApplicationContext will then be stored under the
ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE key.
Issue: SPR-13075, SPR-12553
Spring Framework 4.2 RC1 introduced support for synthesizing an
annotation from an existing annotation in order to provide additional
functionality above and beyond that provided by Java. Specifically,
such synthesized annotations provide support for @AliasFor semantics.
As luck would have it, the same principle can be used to synthesize an
annotation from any map of attributes, and in particular, from an
instance of AnnotationAttributes.
The following highlight the major changes in this commit toward
achieving this goal.
- Introduced AnnotationAttributeExtractor abstraction and refactored
SynthesizedAnnotationInvocationHandler to delegate to an
AnnotationAttributeExtractor.
- Extracted code from SynthesizedAnnotationInvocationHandler into new
AbstractAliasAwareAnnotationAttributeExtractor and
DefaultAnnotationAttributeExtractor implementation classes.
- Introduced MapAnnotationAttributeExtractor for synthesizing an
annotation that is backed by a map or AnnotationAttributes instance.
- Introduced a variant of synthesizeAnnotation() in AnnotationUtils
that accepts a map.
- Introduced findAnnotation(*) methods in AnnotatedElementUtils that
synthesize merged AnnotationAttributes back into an annotation of the
target type.
The following classes have been refactored to use the new support for
synthesizing AnnotationAttributes back into an annotation.
- ApplicationListenerMethodAdapter
- TestAnnotationUtils
- AbstractTestContextBootstrapper
- ActiveProfilesUtils
- ContextLoaderUtils
- DefaultActiveProfilesResolver
- DirtiesContextTestExecutionListener
- TestPropertySourceAttributes
- TestPropertySourceUtils
- TransactionalTestExecutionListener
- MetaAnnotationUtils
- MvcUriComponentsBuilder
- RequestMappingHandlerMapping
In addition, this commit also includes changes to ensure that arrays
returned by synthesized annotations are properly cloned first.
Issue: SPR-13067
This commit introduces first-class support for aliases for annotation
attributes. Specifically, this commit introduces a new @AliasFor
annotation that can be used to declare a pair of aliased attributes
within a single annotation or an alias from an attribute in a custom
composed annotation to an attribute in a meta-annotation.
To support @AliasFor within annotation instances, AnnotationUtils has
been overhauled to "synthesize" any annotations returned by "get" and
"find" searches. A SynthesizedAnnotation is an annotation that is
wrapped in a JDK dynamic proxy which provides run-time support for
@AliasFor semantics. SynthesizedAnnotationInvocationHandler is the
actual handler behind the proxy.
In addition, the contract for @AliasFor is fully validated, and an
AnnotationConfigurationException is thrown in case invalid
configuration is detected.
For example, @ContextConfiguration from the spring-test module is now
declared as follows:
public @interface ContextConfiguration {
@AliasFor(attribute = "locations")
String[] value() default {};
@AliasFor(attribute = "value")
String[] locations() default {};
// ...
}
The following annotations and their related support classes have been
modified to use @AliasFor.
- @ManagedResource
- @ContextConfiguration
- @ActiveProfiles
- @TestExecutionListeners
- @TestPropertySource
- @Sql
- @ControllerAdvice
- @RequestMapping
Similarly, support for AnnotationAttributes has been reworked to
support @AliasFor as well. This allows for fine-grained control over
exactly which attributes are overridden within an annotation hierarchy.
In fact, it is now possible to declare an alias for the 'value'
attribute of a meta-annotation.
For example, given the revised declaration of @ContextConfiguration
above, one can now develop a composed annotation with a custom
attribute override as follows.
@ContextConfiguration
public @interface MyTestConfig {
@AliasFor(
annotation = ContextConfiguration.class,
attribute = "locations"
)
String[] xmlFiles();
// ...
}
Consequently, the following are functionally equivalent.
- @MyTestConfig(xmlFiles = "test.xml")
- @ContextConfiguration("test.xml")
- @ContextConfiguration(locations = "test.xml").
Issue: SPR-11512, SPR-11513