Commit Graph

655 Commits

Author SHA1 Message Date
Sam Brannen 693dcba867 Introduce LoggingResultHandler in Spring MVC Test
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
2015-06-27 21:53:19 +02:00
Sam Brannen 895d43a2b3 Print cookies in human-readable form in Spring MVC Test
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
2015-06-27 02:54:42 +02:00
Juergen Hoeller a2d3c27ed1 Allow MVC handler methods to return any CharSequence type as view name
Issue: SPR-13165
2015-06-26 22:17:53 +02:00
Rossen Stoyanchev 6842fd7fb9 Ensure result ready in asyncDispatch in MockMvc
Issue: SPR-13079
2015-06-25 09:25:21 -04:00
Sam Brannen 10a691bd51 Support inlined SQL statements in @Sql
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
2015-06-23 20:45:00 +02:00
Sam Brannen d0c0d9fc5a Synthesize annotation from defaults
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
2015-06-20 18:27:36 +02:00
Sam Brannen 27d1ce84a3 Polishing 2015-06-20 01:45:46 +02:00
Sam Brannen fb83e83e78 Honor contract of @Repeatable in AnnotationUtils
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
2015-06-20 01:21:39 +02:00
Sam Brannen 23547a72f3 Clean up warnings and polish tests 2015-06-19 14:57:28 +01:00
Sam Brannen 37d61375e2 Fix typo 2015-06-19 14:39:50 +01:00
Sam Brannen ece12f9d37 Synthesize annotation from map w/ minimal attributes
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
2015-06-19 14:27:23 +01:00
Brian Clozel f988151163 Improve charset management in XpathResultMatchers
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
2015-06-17 10:09:54 +02:00
Sam Brannen 68a704373d Retain order of active profiles in the TCF
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
2015-06-15 14:25:06 +01:00
Sam Brannen ea9d7aa337 Polish Javadoc for @TransactionConfiguration 2015-06-14 15:24:20 +02:00
Sam Brannen 32c17bf540 Revise method and parameter names in annotation support
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
2015-06-14 00:34:40 +02:00
Sam Brannen 6b7c1d72e8 Introduce alias for 'value' attribute in @Transactional
Issue: SPR-11393
2015-06-12 22:35:20 +02:00
Sam Brannen f6d2fe471a Proper support for Root WAC in Spring MVC Test
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
2015-06-11 19:54:25 +02:00
Brian Clozel e2c8d3762f Fix tests for SPR-13090 2015-06-11 16:34:33 +02:00
Esko Luontola 89c1674b89 Fix missing space in assertion message 2015-06-01 10:56:53 -04:00
Sam Brannen 6a5b2672e7 Introduce alias for 'value' attribute in @ResponseStatus
Issue: SPR-11393
2015-05-31 17:00:23 +02:00
Sam Brannen 8f233786ed Polishing 2015-05-29 02:05:44 +02:00
Sam Brannen e30c9b2ef3 Synthesize annotation from a map of attributes
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
2015-05-29 01:38:51 +02:00
Sam Brannen ca66e076d1 Support annotation attribute aliases and overrides via @AliasFor
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
2015-05-22 00:01:07 +02:00
Juergen Hoeller b4095c3e1d Class identity comparisons wherever possible
Issue: SPR-12926
2015-05-20 14:34:16 +02:00
Stephane Nicoll cf391f5ce1 polish
Remove unused imports
2015-05-19 08:49:01 +02:00
Sam Brannen 428499a384 Introduce SpringFailOnTimeout(Statement, Method) constructor 2015-05-18 00:43:41 +02:00
Sam Brannen f13f493551 Introduce TestAnnotationUtils to reduce code duplication 2015-05-17 22:24:29 +02:00
Sam Brannen 973582e7df Introduce TestContextManager cache in SpringClassRule
In order to simplify configuration of the SpringMethodRule and to ensure
that the correct TestContextManager is always retrieved for the
currently executing test class, this commit introduces a static
TestContextManager cache in SpringClassRule.

In addition, since it is not foreseen that SpringClassRule and
SpringMethodRule should be able to be subclassed, their internal methods
are now private instead of protected.

Issue: SPR-7731
2015-05-17 17:14:09 +02:00
Sam Brannen 68322fc42a Introduce JUnitTestingUtils to reduce code duplication 2015-05-17 15:47:39 +02:00
Sam Brannen d1b1c4f888 Introduce JUnit Rule alternative to SpringJUnit4ClassRunner
Since Spring Framework 2.5, support for integrating the Spring
TestContext Framework (TCF) into JUnit 4 based tests has been provided
via the SpringJUnit4ClassRunner, but this approach precludes the
ability for tests to be run with alternative runners like JUnit's
Parameterized or third-party runners such as the MockitoJUnitRunner.

This commit remedies this situation by introducing @ClassRule and @Rule
based alternatives to the SpringJUnit4ClassRunner. These rules are
independent of any Runner and can therefore be combined with
alternative runners.

Due to the limitations of JUnit's implementation of rules, as of JUnit
4.12 it is currently impossible to create a single rule that can be
applied both at the class level and at the method level (with access to
the test instance). Consequently, this commit introduces the following
two rules that must be used together.

 - SpringClassRule: a JUnit TestRule that provides the class-level
   functionality of the TCF to JUnit-based tests

 - SpringMethodRule: a JUnit MethodRule that provides the
   instance-level and method-level functionality of the TCF to
   JUnit-based tests

In addition, this commit also introduces the following new JUnit
Statements for use with rules:

 - RunPrepareTestInstanceCallbacks

 - ProfileValueChecker

Issue: SPR-7731
2015-05-16 20:25:12 +02:00
Sam Brannen bccd59e6c8 Use findAnnotationAttributes() where appropriate
This commit updates code that previously used getAnnotationAttributes()
in AnnotatedElementUtils to use findAnnotationAttributes(), where
appropriate.

Issue: SPR-12738
2015-05-14 03:49:59 +02:00
Sam Brannen 6422f7a0a1 Add TODO re: FailOnTimeout.builder() & JUnit 4.12 2015-05-11 18:13:45 +02:00
Sam Brannen d14e29a5c0 Polish SpringJUnit4ClassRunner and related support classes 2015-05-11 13:39:22 +02:00
Sam Brannen cf51f0c0aa Assert pre-conditions in AopTestUtils
Issue: SPR-13005
2015-05-09 21:02:40 +02:00
Sam Brannen efe3a35da8 Introduce AOP testing utilities
This commit introduces support in the spring-test module for obtaining a
reference to the underlying target object hidden behind one or more
proxies.

Specifically this commit introduces AopTestUtils with two methods:

 - getTargetObject(Object)

 - getUltimateTargetObject(Object)

Issue: SPR-13005
2015-05-09 20:32:28 +02:00
Sam Brannen 7a690df925 Remove trailing whitespace from Java source code 2015-05-06 20:08:42 +02:00
Sam Brannen 572cbb0821 Consistently supply test name to @Parameters 2015-05-05 14:07:00 +02:00
Sam Brannen e85e9768c5 Fail if multiple @BootstrapWith's are present
Prior to this commit it was possible for two @BootstrapWith annotations
to be 'present' on a test class -- for example, via competing custom
composed annotations. However, only one of the annotations will ever be
used to bootstrap the TestContext Framework. Thus, in such scenarios
one of the annotations will be silently ignored.

This commit introduces a check for such scenarios. BootstrapUtils'
resolveTestContextBootstrapper() method now throws an
IllegalStateException if more than one @BootstrapWith annotation is
'present' on a given test class.

Issue: SPR-12602
2015-04-26 02:58:07 +02:00
Rob Winch 1a6aeb17e1 Add merged RequestPostProcessor to front on merge
Previously MockHttpServletRequestBuilder merge method would append the
parent's (default) RequestPostProcessor implementations to the end. This
means that the default RequestPostProcessor implementations would override
values set by previous RequestPostProcessor implementations.

This commit ensures that the default RequestPostProcessor are preformed
first so that additional RequestPostProcessor implementations override
the defaults.

Issue: SPR-12945
2015-04-24 13:12:29 -04:00
Sam Brannen ad6bea1cda Support abstract, bridge, & interface methods in AnnotatedElementUtils
This commit introduces support for finding annotations on abstract,
bridge, and interface methods in AnnotatedElementUtils.

 - Introduced dedicated findAnnotationAttributes() methods in
   AnnotatedElementUtils that provide first-class support for
   processing methods, class hierarchies, interfaces, bridge methods,
   etc.

 - Introduced find/get search algorithm dichotomy in
   AnnotatedElementUtils which is visible in the public API as well as
   in the internal implementation. This was necessary in order to
   maintain backwards compatibility with the existing API (even though
   it was undocumented).

 - Reverted all recent changes made to the "get semantics" search
   algorithm in AnnotatedElementUtils in order to ensure backwards
   compatibility, and reverted recent changes to
   JtaTransactionAnnotationParser and SpringTransactionAnnotationParser
   accordingly.

 - Documented internal AnnotatedElementUtils.Processor<T> interface.

 - Enabled failing tests and introduced
   findAnnotationAttributesFromBridgeMethod() test in
   AnnotatedElementUtilsTests.

 - Refactored ApplicationListenerMethodAdapter.getCondition() and
   enabled failing test in TransactionalEventListenerTests.

 - AnnotationUtils.isInterfaceWithAnnotatedMethods() is now package
   private.

Issue: SPR-12738, SPR-11514, SPR-11598
2015-04-24 00:55:48 +02:00
Sam Brannen 69b0791926 Favor local, composed annotations in the TCF
Prior to this commit, AnnotationAttributes retrieved from
MetaAnnotationUtils's AnnotationDescriptor could contain attributes
from the wrong annotation if an inherited annotation shadowed a locally
declared composed annotation.

This commit addresses this issue by invoking the new
getAnnotationAttributes() method in AnnotatedElementUtils that provides
a flag to control whether superclasses should be searched -- which
coincidentally processes local annotations before searching the class
hierarchy.

Issue: SPR-12749, SPR-11598
2015-04-23 02:44:21 +02:00
Sam Brannen 5cbe4b948d Introduce dedicated 'cache' subpackage in the TCF
Since the ContextCache is now a published SPI, it and its collaborators
have been moved to a dedicated 'org.sfw.test.context.cache' subpackage.

Issue: SPR-12683
2015-04-20 21:48:30 +02:00
Sebastien Deleuze 5b0a0f4db5 Support CompletableFuture as alternative to DeferredResult in MVC
Issue: SPR-12597
2015-04-20 14:19:31 +02:00
Sam Brannen e829b2aa1d Polish Javadoc for ContextCache 2015-04-20 00:53:45 +02:00
Sam Brannen 93f403cbf6 Ensure that contexts loaded by the TCF are active
This commit adds an assertion to DefaultTestContext's
getApplicationContext() method to ensure that a context loaded by the
Spring TestContext Framework (TCF) or retrieved from the ContextCache
is still active. This extra check helps to avoid situations where
developers manually close a cached context instead of relying on the
@DirtiesContext support.

Issue: SPR-12932
2015-04-20 00:37:16 +02:00
Sam Brannen d66d160543 Use ConcurrentHashMaps in DefaultContextCache
The changes made in 0cb22fc8f3 would
result in contexts not being properly closed if evicted from the
ConcurrentReferenceHashMap by the Garbage Collector.

This commit reverts those changes and returns to using standard
ConcurrentHashMaps for the time being.

Issue: SPR-7687
2015-04-19 21:06:41 +02:00
Sam Brannen c52a0ccdfd Introduce TestContextManager(TestContextBootstrapper) constructor
Issue: SPR-12683
2015-04-19 20:09:03 +02:00
Sam Brannen 129488cb4f Improve extensibility of TestContext bootstrapping & context caching
- DefaultBootstrapContext and DefaultCacheAwareContextLoaderDelegate
   are now public classes in the 'support' subpackage.

 - Introduced getCacheAwareContextLoaderDelegate() in
   AbstractTestContextBootstrapper as an extension point for configuring
   custom ContextCache support.

 - Introduced reflection-based createBootstrapContext() utility method
   in BootstrapUtils; TestContextManager now delegates to BootstrapUtils
   in order to avoid package cycles.

 - Introduced logStatistics() method in the ContextCache API and defined
   statistics logging category as a constant.

 - DefaultCacheAwareContextLoaderDelegate now delegates to
   ContextCache.logStatistics().

Issue: SPR-12683
2015-04-19 19:23:56 +02:00
Sam Brannen e6c24f7167 Convert ContextCache to interface with default implementation
- ContextCache is now a public interface.

 - Introduced public DefaultContextCache implementation in the 'support'
   subpackage.

Issue: SPR-12683
2015-04-19 19:23:42 +02:00
Sam Brannen c9d597f519 Introduce createBootstrapContext() extension in TestContextManager
Issue: SPR-12683
2015-04-18 23:47:11 +02:00
Sam Brannen 0b054f9fbd Improve Javadoc for TestContextBootstrapper 2015-04-18 23:45:34 +02:00
Sam Brannen 186abcb054 Introduce buildTestContext() in TestContextBootstrapper
This commit moves the responsibility of building a TestContext from the
TestContextManager to a TestContextBootstrapper.

In addition, DefaultTestContext is now a public class residing in the
"support" subpackage.

Issue: SPR-12683
2015-04-18 23:15:30 +02:00
Sam Brannen 0392a88c69 Move static ContextCache to DefaultCacheAwareContextLoaderDelegate
Issue: SPR-12683
2015-04-18 20:23:24 +02:00
Sam Brannen 0e287c1a90 Introduce resetContextCache() in ContextCacheTestUtils 2015-04-18 19:16:59 +02:00
Sam Brannen dc345dcb3d Polish TestContextManager 2015-04-18 18:50:37 +02:00
Sam Brannen 0cb22fc8f3 Use SoftReferences for context caching in the TCF
Prior to this commit, the ContextCache in the Spring TestContext
Framework (TCF) cached ApplicationContexts in a ConcurrentHashMap using
strong references. This practice can occasionally lead to
OutOfMemoryErrors when running a large number of tests in a test suite
with varying context configuration since the context cache becomes
overpopulated over time.

This commit addresses this issue by using Spring's
ConcurrentReferenceHashMap which uses SoftReferences for both the keys
(i.e., MergedContextConfiguration instances) and values (i.e.,
ApplicationContexts) stored in the map that backs the ContextCache.

Issue: SPR-7687
2015-04-18 17:36:39 +02:00
Sam Brannen 2a4f4cd258 Introduce reset() method in ContextCache 2015-04-17 22:51:04 +02:00
Sam Brannen 3c5a9b4e1d Introduce class-level @DirtiesContext tests for TestNG
Prior to this commit, ClassLevelDirtiesContextTests existed for
verifying the expected behavior of @DirtiesContext declared at the
class level in conjunction with JUnit and SpringJUnit4ClassRunner.

This commit introduces analogous tests for TestNG in the new
ClassLevelDirtiesContextTestNGTests class.

Furthermore, ContextCacheTestUtils and TrackingTestNGTestListener have
been introduced to reduce code duplication across the test suite.

Issue: SPR-12918
2015-04-17 17:26:38 +02:00
Sam Brannen c006b74e91 Make AbsTstCtxBootstrapper.resolveContextLoader protected
This commit increases the extensibility of
AbstractTestContextBootstrapper by making the resolveContextLoader()
and resolveExplicitContextLoaderClass() methods protected instead of
private.

Furthermore, resolveContextLoader() now throws an IllegalStateException
if getDefaultContextLoaderClass() returns null.

Issue: SPR-12682
2015-04-15 00:37:43 +02:00
Sam Brannen 063ef240c1 Support static fields in ReflectionTestUtils
Prior to this commit it was possible to set or get a static field using
ReflectionTestUtils but only if an instance of the target class was
available.

This commit introduces dedicated support for setting and getting static
fields in ReflectionTestUtils when only the target class is available.

Furthermore, this commit increases the robustness of
ReflectionTestUtilsTests regarding expected exceptions and simplifies
the Javadoc for ReflectionTestUtils.

Issue: SPR-6792
2015-04-08 22:32:00 -04:00
Rossen Stoyanchev 0b8554f94a Leave query un-encoded in MockMvc request builder
Issue: SPR-12880
2015-04-06 22:43:25 -04:00
Juergen Hoeller 4e1af7d195 Deprecated MatcherAssertionErrors in favor of the original org.hamcrest.MatcherAssert (v1.3)
As of JUnit 4.9 / Hamcrest 1.3, there is no real need for a custom copy of that class anymore.
2015-03-25 00:04:47 +01:00
Juergen Hoeller b2308926bc Restored isTypeMatch null behavior and refined typeToMatch parameter name
Issue: SPR-12147
2015-03-23 21:57:03 +01:00
Brian Clozel 7f845f7b5e Fix failing HeaderAssertionTests
Since SPR-11792, Last-Modified and ETag headers are also written in
`HTTP 304 Not Modified` responses. This is expected as per
https://tools.ietf.org/html/rfc7232#section-4.1 .

Those tests expected "Last-Modified" to be missing in case of HTTP 304
responses, which is not the case anymore since 953608ec .

Issue: SPR-11792
2015-03-23 18:50:32 +01:00
Sam Brannen e086a637d5 Introduce BEFORE METHOD/CLASS modes in @DirtiesContext
Prior to this commit, @DirtiesContext could only be used to close a
test ApplicationContext after an entire test class or after a test
method; however, there are some use cases for which it would be
beneficial to close a test ApplicationContext before a given test class
or test method -- for example, if some rogue (i.e., yet to be
determined) test within a large test suite has corrupted the original
configuration for the ApplicationContext.

This commit provides a solution to such testing challenges by
introducing the following modes for @DirtiesContext.

 - MethodMode.BEFORE_METHOD: configured via the new methodMode attribute

 - ClassMode.BEFORE_CLASS and ClassMode.BEFORE_EACH_TEST_METHOD: both
   configured via the existing classMode attribute

Issue: SPR-12429
2015-03-22 21:33:20 +01:00
Sam Brannen 6028a64444 Polish Javadoc for TestContext 2015-03-22 21:33:06 +01:00
Sam Brannen 3d2bde7156 Add tests that use the new generate-name attribute
This commit updates the Spr8849Tests test suite to include XML
configuration that guarantees that a unique database name is always
automatically generated (via the new 'generate-name' attribute that was
introduced in SPR-8849) while reusing the same bean name (i.e.,
'dataSource').

Issue: SPR-8849
2015-03-21 00:39:54 +01:00
Rossen Stoyanchev f06dffb714 Improve MockHttpServletRequest/Response charset parsing
Issue: SPR-12677
2015-03-20 16:12:46 -04:00
Sam Brannen ab771dfd97 Refactor tests to use the new database-name attribute
This commit refactors the XML configuration used by the tests in the
Spr8849Tests test suite so that a unique database name is always
generated (via the new 'database-name' attribute that was introduced in
SPR-12835) while reusing the same bean name (i.e., 'dataSource').

This is a much more robust alternative to the previous work-around
since the name of the DataSource does not randomly change across
application contexts, thus allowing proper autowiring by name and bean
referencing within XML configuration.

Issue: SPR-8849
2015-03-20 17:11:52 +01:00
Juergen Hoeller 778a01943b ResolvableType-based type matching at the BeanFactory API level
Issue: SPR-12147
2015-03-18 23:05:13 +01:00
Juergen Hoeller bc6a98c144 Polishing (in particular updating javadoc references to Apache Commons) 2015-03-13 18:19:10 +01:00
Sam Brannen e24a7ded62 Simplify Groovy ContextLoaders in the TCF
This commit simplifies the implementations of loadBeanDefinitions() in
GenericGroovyXmlContextLoader and GenericGroovyXmlWebContextLoader.

Due to the recent bug fix for GroovyBeanDefinitionReader regarding full
support for XML config files, these Groovy context loaders can now
simply use a GroovyBeanDefinitionReader instead of a
GroovyBeanDefinitionReader plus an XmlBeanDefinitionReader.

Issue: SPR-12769
2015-02-28 23:28:55 +01:00
Sam Brannen 2ba1151b7f Support XML config fully in web integration tests
Prior to this commit, it was impossible to use all features of XML
configuration (e.g., the <qualifier> tag) in web-based integration
tests (loaded using @WebAppConfiguration, @ContextConfiguration, etc.)
if the Groovy library was on the classpath. The reason is that the
GroovyBeanDefinitionReader used internally by
GenericGroovyXmlWebContextLoader disables XML validation for its
internal XmlBeanDefinitionReader, and this prevents some XML
configuration features from working properly. For example, the default
value for the 'type' attribute (defined in the spring-beans XSD) of the
<qualifier> tag gets ignored, resulting in an exception when the
application context is loaded.

This commit addresses this issue by refactoring the implementation of
loadBeanDefinitions() in GenericGroovyXmlWebContextLoader to use an
XmlBeanDefinitionReader or GroovyBeanDefinitionReader depending on the
file extension of the resource location from which bean definitions
should be loaded. This aligns the functionality of
GenericGroovyXmlWebContextLoader with the existing functionality of
GenericGroovyXmlContextLoader.

Issue: SPR-12768
2015-02-28 19:06:40 +01:00
Sam Brannen fa5ea38210 Delete unused import in AsyncTests 2015-02-28 19:05:37 +01:00
Stephane Nicoll babbf6e871 Harmonize resources location
Issue: SPR-12766
2015-02-28 10:32:40 +01:00
Rossen Stoyanchev c48858c972 Prevent ISE in the MockMvc PrintingResultHandler
Issue: SPR-12735
2015-02-27 11:30:12 -05:00
Rossen Stoyanchev e13c300b53 Fix white space issues 2015-02-27 10:53:34 -05:00
Rossen Stoyanchev 2beca4d75e Update javadoc 2015-02-26 11:45:50 -05:00
Rossen Stoyanchev 2dd5875964 Support @ControllerAdvice in StandaloneMockMvcBuilder
Issue: SPR-12751
2015-02-25 16:57:58 -05:00
Sam Brannen 42af33034d Make TestPropertySourceUtils more robust
- Added assertions for pre-conditions on method arguments for all
   public utility methods.

 - Introduced additional tests in TestPropertySourceUtilsTests to verify
   the new pre-conditions.

 - Introduced INLINED_PROPERTIES_PROPERTY_SOURCE_NAME constant for the
   name of the MapPropertySource created from inlined properties; the
   name therefore no longer contains the inlined properties, but the
   original values of the inlined properties can now be logged at debug
   level.

 - Simplified tests in InlinedPropertiesTestPropertySourceTests.

Issue: SPR-12721
2015-02-17 19:42:52 +01:00
Sam Brannen 0267715c9d Polish Javadoc for @TestPropertySource 2015-02-17 19:32:19 +01:00
Sam Brannen 75e0bc9271 Open up TestPropertySourceUtils for public consumption
Spring Framework 4.1 introduced support for @TestPropertySource;
however, the utilities used to parse inlined properties and add test
property sources to the environment are currently private which
prevents reuse by third-party frameworks like Spring Boot.

This commit addresses this issue by making such utilities public.

 - TestPropertySourceUtils is now a public class.

 - Various utility methods in TestPropertySourceUtils have been made
   public.

 - addResourcePropertySourcesToEnvironment() has been renamed to
   addPropertiesFilesToEnvironment().

 - extractEnvironmentProperties() has been renamed to
   convertInlinedPropertiesToMap().

 - All public methods in TestPropertySourceUtils are now fully
   documented.

Issue: SPR-12721
2015-02-17 03:09:24 +01:00
Sam Brannen d6a799ad4a Preserve ordering of inlined props in @TestPropertySource
The initial implementation for adding inlined properties configured via
@TestPropertySource to the context's environment did not preserve the
order in which the properties were physically declared. This makes
@TestPropertySource a poor testing facility for mimicking the
production environment's configuration if the property source mechanism
used in production preserves ordering of property names -- which is the
case for YAML-based property sources used in Spring Boot, Spring Yarn,
etc.

This commit addresses this issue by ensuring that the ordering of
inlined properties declared via @TestPropertySource is preserved.
Specifically, the original functionality has been refactored. extracted
from AbstractContextLoader, and moved to TestPropertySourceUtils where
it may later be made public for general purpose use in other frameworks.

Issue: SPR-12710
2015-02-16 20:26:49 +01:00
Sam Brannen 67934a22e2 Add further regression tests for @TestPropertySource
This commit introduces further regression tests to ensure proper parsing
of inlined properties configured via @TestPropertySource. Specifically,
these additional tests ensure that we do not introduce a bug like the
one raised in Spring Boot issue #1110 [0].

[0] https://github.com/spring-projects/spring-boot/issues/1110

Issue: SPR-12710
2015-02-12 20:24:06 +01:00
Stephane Nicoll f0fca890bb Annotation-based event listeners
Add support for annotation-based event listeners. Enabled automatically
when using Java configuration or can be enabled explicitly via the
regular <context:annotation-driven/> XML element. Detect methods of
managed beans annotated with @EventListener, either directly or through
a meta-annotation.

Annotated methods must define the event type they listen to as a single
parameter argument. Events are automatically filtered out according to
the method signature. When additional runtime filtering is required, one
can specify the `condition` attribute of the annotation that defines a
SpEL expression that should match to actually invoke the method for a
particular event. The root context exposes the actual `event`
(`#root.event`) and method arguments (`#root.args`). Individual method
arguments are also exposed via either the `a` or `p` alias (`#a0` refers
to the first method argument). Finally, methods arguments are exposed via
their names if that information can be discovered.

Events can be either an ApplicationEvent or any arbitrary payload. Such
payload is wrapped automatically in a PayloadApplicationEvent and managed
explicitly internally. As a result, users can now publish and listen
for arbitrary objects.

If an annotated method has a return value, an non null result is actually
published as a new event, something like:

@EventListener
public FooEvent handle(BarEvent event) { ... }

Events can be handled in an aynchronous manner by adding `@Async` to the
event method declaration and enabling such infrastructure. Events can
also be ordered by adding an `@Order` annotation to the event method.

Issue: SPR-11622
2015-02-10 09:13:02 +01:00
Sam Brannen 2d918380f0 Support @Configuration as meta-annotation in the TCF
Spring Framework 4.0 introduced support for using test-related
annotations as meta-annotations in the Spring TestContext Framework
(TCF) in order to create custom composed annotations within a test
suite; however, the detection of default @Configuration classes in test
classes was not updated to search for @Configuration declared as a
meta-annotation. Specifically, AnnotationConfigContextLoaderUtils
invokes Class.isAnnotated() which only searches for annotations
declared directly on the class in question.

This commit addresses this issue by refactoring the
isDefaultConfigurationClassCandidate() method in
AnnotationConfigContextLoaderUtils so that it uses
AnnotationUtils.findAnnotation() instead of Class.isAnnotated() for
detecting the presence of the @Configuration annotation, either
directly or as a meta-annotation.

Issue: SPR-12659
2015-01-23 22:13:04 +01:00
Sam Brannen c5c32ec206 Refer to static nested classes, not static inner classes
Various parts of the reference manual as well as the Javadoc for
AnnotationConfigContextLoaderUtils improperly refer to "static inner
classes" even though this terminology does not exist in Java. The Java
Language Specification explicitly refers to such classes as "static
nested classes." An "inner class" must be non-static by definition.
2015-01-23 21:41:12 +01:00
Maciej Ziarko 81c750fb1c Fix Javadoc examples 2015-01-17 13:48:50 +01:00
Sam Brannen 276712dcd1 Enable reuse of DefaultActiveProfilesResolver
In order to allow DefaultActiveProfilesResolver to be reused (e.g., via
extension or delegation), the check which asserts that the 'resolver'
attribute of @ActiveProfiles is not set to a customer resolver class
has been removed.

Issue: SPR-12611
2015-01-10 20:36:48 +01:00
Sam Brannen cf7a7932f3 Polish TimedSpringRunnerTests 2015-01-10 17:52:41 +01:00
Sam Brannen b81c522ee1 Handle exceptions properly in SpringJUnit4ClassRunner
JUnit 4.9 introduced a regression in BlockJUnit4ClassRunner.runChild()
such that exceptions thrown from methodBlock() cause the current test
execution to abort immediately. As a result, the failing test method is
unrooted, and subsequent test methods are never invoked. Furthermore,
RunListeners registered with JUnit are not properly notified.

In conjunction with SPR-11908, SpringJUnit4ClassRunner was updated to
use the aforementioned changes to BlockJUnit4ClassRunner.runChild().
Consequently, SpringJUnit4ClassRunner now suffers from the same
regression.

This commit addresses this issue by ensuring that any exceptions thrown
during the invocation of methodBlock() are properly wrapped in a JUnit
Fail Statement.

Issue: SPR-12613
2015-01-10 17:51:51 +01:00
Juergen Hoeller 27b4909f46 Polishing
(cherry picked from commit 8c700b1)
2014-12-30 21:11:56 +01:00
Juergen Hoeller 9ac02b319d Remove pre-3.2 deprecated classes and methods
Issue: SPR-12578
2014-12-30 20:05:15 +01:00
Sebastien Deleuze d8a01cb04a Polish MockMvcBuilders tests 2014-12-22 13:51:56 +01:00
Sebastien Deleuze 32aafb21ff Set ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE in DefaultMockMvcBuilder
Issue: SPR-12553
2014-12-22 13:39:21 +01:00
Sam Brannen e901abee06 Fix JavaDoc in TestExecutionListener regarding Ordered 2014-12-08 23:51:40 +01:00
Sam Brannen 1988f8c75f Polish Javadoc for ContextCache 2014-11-09 23:30:16 +01:00
Juergen Hoeller 74500ec8da Avoid unnecessary synchronization in ContextCache, plus forward-ported polishing
Issue: SPR-12409
2014-11-06 17:15:30 +01:00
Rossen Stoyanchev 794566abf5 Fix failing test 2014-11-05 21:17:32 -05:00
Rossen Stoyanchev 7f4bf41c23 Improve exception message
Issue: SPR-12230
2014-11-05 17:32:39 -05:00
Sam Brannen da04362a5e Log context cache statistics in the TCF
Prior to this commit, finding out how many application contexts had
been loaded within a test suite required the use of reflection and a
bit of hacking.

This commit addresses this issue by logging ContextCache statistics
whenever an application context is loaded by the Spring TestContext
Framework (TCF).

The log output can be enabled by setting the
"org.springframework.test.context.cache" logging category to DEBUG.

Issue: SPR-12409
2014-11-03 15:26:44 +01:00
Juergen Hoeller bba38b8862 MockHttpServletRequestBuilder allows for specifying content type as String value
Issue: SPR-12405
2014-11-01 23:01:26 +01:00
Sam Brannen 2f03945410 Delete unused imports in spring-test 2014-10-31 00:26:13 +01:00
Sam Brannen fc7e60678c Fix Javadoc in MockHttpServletRequestBuilder
Class-level Javadoc for MockHttpServletRequestBuilder now correctly
refers to MockMvcRequestBuilders instead of MockMvcBuilders.

Issue: SPR-12393
2014-10-30 00:07:01 +01:00
Juergen Hoeller 1146d5ba1d Polishing 2014-10-29 22:44:59 +01:00
Juergen Hoeller 065104a485 Restored compatibility with JsonPath 0.9.x
Issue: SPR-12299
2014-10-21 12:37:56 +02:00
Juergen Hoeller 8325b10080 Consistent formatting of license headers, package javadocs, and import declarations 2014-10-21 01:44:07 +02:00
Juergen Hoeller 77a62ec8b8 Polishing 2014-10-20 17:42:18 +02:00
Juergen Hoeller d501137f4e Consistently accept empty Content-Type header and empty character encoding
Issue: SPR-12173
2014-10-14 14:26:07 +02:00
Sam Brannen 25d13ac41e Sensible defaults for Servlet & Filter registrations in mock
Prior to this commit, the getter methods in MockServletContext threw an
UnsupportedOperationException when trying to retrieve Servlet and
Filter registrations.

This commit improves the behavior of these methods by returning null
when a single registration is requested and an empty map when all
registrations are requested. This is now in line with the Javadoc for
ServletContext. Note, however, that the corresponding setter methods
still throw UnsupportedOperationExceptions which is suitable behavior
for a mock.

Issue: SPR-12290
2014-10-02 14:03:39 +02:00
Sam Brannen 0026d8faf8 Update package-info for org.springframework.test 2014-09-22 15:06:43 +02:00
Sam Brannen 0083cc0a01 Add missing package-info files in spring-test 2014-09-22 15:06:43 +02:00
Juergen Hoeller 16325c2eaa Polishing 2014-09-20 00:29:16 +02:00
Sam Brannen 703cc0d6ae Polish Javadoc for MergedContextConfiguration 2014-08-31 21:03:38 +02:00
Sam Brannen f9855b7901 Polish Javadoc for @Sql and SqlScriptsTestExecutionListener 2014-08-31 17:17:04 +02:00
Sam Brannen 8008e466aa Refactor AssertThrows to support Throwable
Prior to this commit, AssertThrows in the spring-test module only
supported Exception; however, there are legitimate test cases where the
subject under test (SUT) may potentially throw a subclass of Throwable.

This commit refactors AssertThrows so that it supports exceptions of
type Throwable instead of the limiting support for Exception.
Furthermore, AssertThrows has been refactored to use generics (e.g.,
Class<? extends Throwable> instead of merely Class).

Issue: SPR-6362
2014-08-29 16:00:01 +02:00
Sam Brannen 1bce6ac60c Discontinue use of deprecated AssertThrows
This commit refactors ReflectionTestUtilsTests so that it no longer uses
the deprecated AssertThrows class.
2014-08-29 15:28:19 +02:00
Sam Brannen 27be396b06 Update Javadoc for AssertThrows 2014-08-29 15:28:19 +02:00
Sam Brannen 0b0ddc6ed1 Honor scheme in MockHttpServletRequest.isSecure()
Prior to this commit the implementation of isSecure() in
MockHttpServletRequest simply returned the value of the 'secure'
boolean flag. Thus setting the scheme to 'https' had no effect on the
value returned by isSecure() even though most non-mock implementations
(e.g., Tomcat, Jetty, etc.) base the return value on the actual scheme
in the request.

This commit makes the behavior of MockHttpServletRequest.isSecure()
more intuitive by honoring both the 'secure' boolean flag and the
current value of the scheme.

Issue: SPR-12098
2014-08-28 15:05:36 +02:00
Sam Brannen d5c6bcb901 How to register MIME types in MockServletContext
Prior to this commit, it was unclear that it was possible to register
custom MIME types when using MockServletContext.

This commit updates the Javadoc for MockServletContext.getMimeType()
with an example of how to achieve this using the MimetypesFileTypeMap
from the Java Activation Framework.

Issue: SPR-12126
2014-08-27 00:23:01 +02:00
Sam Brannen 2f2fe9bd05 Verify custom MIME type support in MockServletContext 2014-08-26 23:54:02 +02:00
Sam Brannen 2963fd9e5a Fix broken Javadoc link in @TestPropertySource 2014-08-24 18:12:38 +02:00
Sam Brannen 110be33337 Honor Host header for server name/port in MckHtSrvRq
Prior to this commit, the getServerName() and getServerPort() methods
in MockHttpServletRequest simply returned the 'mocked' serverName and
serverPort but ignored the 'Host' header entirely. Per the Servlet
specification, however, these methods must parse the server name or
port from the 'Host' header if it is present and otherwise fall back to
the resolved server name or port.

This commit fixes this by ensuring that getServerName() and
getServerPort() properly parse the server's name or port from the
'Host' header if it is present in the request. If the 'Host' header is
not present, MockHttpServletRequest falls back to returning the
'mocked' serverName and serverPort.

Issue: SPR-12088
2014-08-19 00:08:09 +02:00
Sam Brannen e1d7f08d7b Relax XML content type expectations in tests
Requests in XmlContentAssertionTests and XpathAssertionTests now accept
"application/xml;charset=UTF-8" in addition to "application/xml".
2014-08-15 20:56:38 +02:00
Sam Brannen a91ab34866 Polish Javadoc and formatting in @TestExecutionListeners 2014-08-15 13:38:13 +02:00
Sam Brannen 8b86519b94 Polishing 2014-08-15 02:50:03 +02:00
Sam Brannen 66250b1f8e Support merging custom TELs with default TELs
Prior to this commit, if a custom TestExecutionListener was registered
via @TestExecutionListeners the defaults would not be registered. Thus,
if a user wanted to declare a custom listener and use the default
listeners, the user was forced to manually declare all default
listeners in addition to any custom listeners. This unfortunately
required that the user know exactly which listeners were registered by
default. Moreover, the set of default listeners can change from release
to release, and with the support for automatic discovery of default
listeners introduced in SPR-11466 it is no longer even possible to know
what the set of default TestExecutionListeners is before runtime.

This commit addresses this issue by introducing a mechanism for merging
custom declared listeners with the defaults for the current
environment. Specifically, @TestExecutionListeners supports a new
MergeMode that is used to control whether or not explicitly declared
listeners are merged with the default listeners when
@TestExecutionListeners is declared on a class that does not inherit
listeners from a superclass.

Issue: SPR-8854
2014-08-15 02:21:42 +02:00
Sam Brannen e6d16148e5 Support automatic discovery of default TELs
Prior to this commit, there was no declarative mechanism for a custom
TestExecutionListener to be registered as a default
TestExecutionListener.

This commit introduces support for discovering default
TestExecutionListener implementations via the SpringFactoriesLoader
mechanism. Specifically, the spring-test module declares all core
default TestExecutionListeners under the
org.springframework.test.context.TestExecutionListener key in its
META-INF/spring.factories properties file, and third-party frameworks
and developers can contribute to the list of default
TestExecutionListeners in the same manner.

 - AbstractTestContextBootstrapper uses the SpringFactoriesLoader to
   look up the class names of all registered default
   TestExecutionListeners and sorts the instantiated listeners using
   AnnotationAwareOrderComparator.

 - DefaultTestContextBootstrapper and WebTestContextBootstrapper now
   rely on the SpringFactoriesLoader mechanism for finding default
   TestExecutionListeners instead of hard coding fully qualified class
   names.

 - To ensure that default TestExecutionListeners are registered in the
   correct order, each can implement Ordered or declare @Order.

 - AbstractTestExecutionListener and all default TestExecutionListeners
   provided by Spring now implement Ordered with appropriate values.

 - Introduced "copy constructors" in MergedContextConfiguration and
   WebMergedContextConfiguration

 - SpringFactoriesLoader now uses AnnotationAwareOrderComparator
   instead of OrderComparator.

Issue: SPR-11466
2014-08-14 22:29:21 +02:00
Sam Brannen 181299cc6c Improve ex msg when locations & classes are declared in test hierarchy
Prior to this commit, if both locations and classes were declared via
@ContextConfiguration at differing levels in a test class hierarchy,
the exception message stated that neither of the default context
loaders was able to load an ApplicationContext from the merged context
configuration, but the message didn't explain why.

This commit adds an explicit check for such scenarios and provides a
more informative exception message similar to the following:

"Neither X nor Y supports loading an ApplicationContext from
[MergedContextConfiguration ...]: declare either 'locations' or
'classes' but not both."

Issue: SPR-12060
2014-08-14 01:23:11 +02:00
Sam Brannen f4c23d8715 Delete trailing white space in spring-test 2014-08-14 00:30:50 +02:00
Sam Brannen 2cbd5ba993 Clean up regarding deprecated HttpStatus.MOVED_TEMPORARILY 2014-08-14 00:29:09 +02:00
Sam Brannen 3e2138855a Add @Deprecated to WebMergedContextConfiguration constructor 2014-08-14 00:22:12 +02:00
Sam Brannen 2cf4147ba8 Introduce @TestPropertySource support in the TCF
Spring Framework 3.1 introduced an Environment abstraction with support
for hierarchical PropertySources that can be configured
programmatically as well as declaratively via the @PropertySource
annotation. However, prior to this commit, there was no way to
declaratively configure PropertySources in integration tests in the
Spring TestContext Framework (TCF).

This commit introduces declarative support for PropertySources in the
TCF via a new class-level @TestPropertySource annotation. This
annotation provides two options for declaring test property sources:

 - The 'locations' attribute allows developers to declare external
   resource locations for test properties files.

 - The 'properties' attribute allows developers to declare inlined
   properties in the form of key-value pairs.

Test properties files are added to the Environment before all other
property sources and can therefore override system and application
property sources. Similarly, inlined properties are added to the
Environment before all other property sources and can therefore
override system property sources, application property sources, and
test properties files.

Specifically, this commit introduces the following major changes:

 - Introduced @TestPropertySource annotation along with internal
   TestPropertySourceAttributes, MergedTestPropertySources, and
   TestPropertySourceUtils for working with test property sources
   within the TCF.

 - All TestContextBootstrappers have been modified to support the
   merged property resource locations and inlined properties from
   @TestPropertySource.

 - MergedContextConfiguration (and consequently the context caching
   key) is now additionally based on the merged property resource
   locations and inlined properties from @TestPropertySource. The same
   applies to WebMergedContextConfiguration.

 - AbstractContextLoader's prepareContext() method now adds
   PropertySources for all resource locations and inlined properties
   from the supplied MergedContextConfiguration to the Environment of
   the supplied ApplicationContext. All subclasses of
   AbstractGenericContextLoader and AbstractGenericWebContextLoader
   therefore automatically provide support for @TestPropertySource.

Issue: SPR-12051
2014-08-14 00:01:38 +02:00
Juergen Hoeller fd5dbddac4 BeanFactory supports bean creation arguments for by-type lookup as well
Issue: SPR-11235
2014-08-12 22:07:12 +02:00
Phillip Webb ac8326d2df Polish mockito usage
Consistent use of BDDMockito rather than standard Mockito.
2014-08-11 16:23:11 -07:00
Juergen Hoeller 53192bb6f4 Polishing 2014-08-09 00:28:13 +02:00
Juergen Hoeller ad475ffadf Consistent vararg declarations for String array setters 2014-08-08 17:17:09 +02:00
Stephane Nicoll 0b2c0cfb4f Fix some warning 2014-08-07 15:44:39 +02:00
Sebastien Deleuze 3922f6fc53 Update references to RFC 2616
Replace references to the old RFC 2616 (HTTP 1.1) with references
to the new RFCs 7230 to 7235.

This commit also deprecates:
 - HttpStatus.USE_PROXY
 - HttpStatus.REQUEST_ENTITY_TOO_LARGE in favor of HttpStatus.PAYLOAD_TOO_LARGE
 - HttpStatus.REQUEST_URI_TOO_LONG in favor of HttpStatus.URI_TOO_LONG

Issue: SPR-12067
2014-08-07 14:50:45 +02:00
Stephane Nicoll 3da68cfe21 Remove unused imports 2014-08-04 14:13:40 +02:00
Rossen Stoyanchev b5e1198bd2 Fix white spaces 2014-08-01 17:12:43 -04:00
Jakub Narloch a11b62540a Support HTTP HEAD method in MockMvcRequestBuilders
Surprisingly until now the MockMvcRequestBuilders did not have methods
for HTTP HEAD. This change adds such methods to the  API making it
consistent with other HTTP method types.

Issue: SPR-12055
2014-08-01 17:03:12 -04:00
Juergen Hoeller 8f484d382e Polishing 2014-07-29 11:42:37 +02:00
Juergen Hoeller 8cc0fa5ae1 Polishing 2014-07-28 22:05:40 +02:00
Sam Brannen 7971f6b638 Document that mock request doesn't support Accept-Language header
This commit updates the Javadoc for getLocale() and getLocales() in
MockHttpServletRequest to point out that the mock implementation does
not comply with the the Servlet specification with regard to the
Accept-Language header.

Issue: SPR-12043
2014-07-28 19:12:39 +03:00
Sam Brannen 9bf73f3ab8 Document default locale in MockHttpServletRequest
This commit updates the class-level Javadoc for MockHttpServletRequest
with information regarding the default locale for the mocked server.

Issue: SPR-11701
2014-07-28 19:07:26 +03:00
Sam Brannen f862a009a7 Groovy loader should delegate to XML loader in the TCF
If a resource location in the MergedContextConfiguration has a ".xml"
extension, the GenericGroovyXmlContextLoader now delegates to a
dedicated XmlBeanDefinitionReader for loading bean definitions from that
resource, thus preserving XML validation for all XML resource locations.
For all other extensions (presumably only ".groovy"), the
GenericGroovyXmlContextLoader delegates to a GroovyBeanDefinitionReader.

Issue: SPR-11233
2014-07-28 17:55:57 +03:00
Sam Brannen 0ad5de3f77 Document default TELs in AbstTxTestNGSpringContextTests 2014-07-24 19:04:11 +02:00
Sam Brannen 5a483f347a Polishing 2014-07-24 19:02:10 +02:00
Sam Brannen d144e2918e Document default TELs in AbstTxJUnit4SpringContextTests 2014-07-24 18:58:59 +02:00
Sam Brannen 0d4526e050 Update Javadoc re: minimum JUnit 4.9 dependency 2014-07-24 18:54:13 +02:00
Sam Brannen 170d6c9fb9 Delete trailing whitespace in spring-test 2014-07-24 18:13:38 +02:00
Sam Brannen 35c372f200 Support Groovy scripts in the TCF
Spring Framework 4.0 introduced first-class support for a Groovy-based
DSL for defining the beans for an ApplicationContext. However, prior to
this commit, the Spring TestContext Framework (TCF) did not provide any
out-of-the-box support for using Groovy scripts as path-based resource
locations when loading an application context for tests.

This commit addresses this issue by introducing first-class support for
using Groovy scripts to load the ApplicationContext for integration
tests managed by the TCF. Specifically, the following changes have been
made in the TCF to support Groovy scripts.

 - Introduced getResourceSuffixes() in AbstractContextLoader in order
   to support multiple resource suffixes in the default detection
   process. This feature is used by the new Groovy/Xml context loaders.

 - Introduced GenericGroovyXmlContextLoader and
   GenericGroovyXmlWebContextLoader which support both Groovy scripts
   and XML config files for loading bean definitions. Furthermore,
   these loaders support "-context.xml" and "Context.groovy" as
   resource suffixes when detecting defaults. Note that a default XML
   config file will be detected before a default Groovy script.

 - DelegatingSmartContextLoader and WebDelegatingSmartContextLoader now
   use reflection to choose between using GenericGroovyXmlContextLoader
   and GenericGroovyXmlWebContextLoader vs. GenericXmlContextLoader and
   GenericXmlWebContextLoader as their XML loaders, depending on
   whether Groovy is present in the classpath.

 - Groovy scripts can be configured via the 'locations' or 'value'
   attributes of @ContextConfiguration and can be mixed seamlessly with
   XML config files.

Issue: SPR-11233
2014-07-24 17:04:40 +02:00
Sam Brannen b75eb60943 Clean up Spring MVC Test Framework code
- Formatting
 - Suppress warnings
 - Remove unused imports
2014-07-24 14:12:14 +02:00
Rossen Stoyanchev 71b63cd972 Update MockMvcConfigurer support
This is a follow-up on the commit introducing MockMvcConfigurer:
c2b0fac852

This commit refines the MockMvcConfigurer contract to use (the new)
ConfigurableMockMvcBuilder hence not requiring downcasting to
AbstractMockMvcBuilder.

The same also no longer passes the "default" RequestBuilder which would
also require a downcast, but rather allows a RequestPostProcessor to be
returned so that a 3rd party framework or application can modify any
property of every performed MockHttpServletRequest.

To make this possible the new SmartRequestBuilder interface separates
request building from request post processing while the new
ConfigurableSmartRequestBuilder allows adding a RequestPostProcessor
to a MockMvcBuilder.

Issue: SPR-11497
2014-07-22 13:41:22 -04:00
Sam Brannen 3013558e3d Update Javadoc for SqlScriptsTestExecutionListener 2014-07-20 22:03:31 +02:00
Sam Brannen a10537447e Polish Javadoc for TestTransaction 2014-07-19 10:59:10 +02:00
Sam Brannen 7d2ef69c6d Polish Javadoc for TransactionalTestExecutionListener 2014-07-19 10:52:46 +02:00
Sam Brannen 97dad7e2ea Polish Javadoc for TestExecutionListener 2014-07-19 10:45:53 +02:00
Sam Brannen b16e6cc44e Improve documentation for tx support in the TCF
Overhauled class-level Javadoc for TransactionalTestExecutionListener:

 - Reorganized content.
 - Added headings to paragraphs.
 - Documented TestTransaction support.

Issue: SPR-11941
2014-07-19 10:45:27 +02:00
Sam Brannen 526b4b647f Improve Javadoc for TransactionalTestExecutionListener 2014-07-18 17:50:12 +02:00
Juergen Hoeller 9d6c38bd54 Consistent bracket alignment 2014-07-18 17:21:58 +02:00
Sam Brannen 3e5946db37 Polish log statements for TransactionContext 2014-07-18 17:09:53 +02:00
Sam Brannen 7808996d71 Polishing 2014-07-18 17:02:45 +02:00
Sam Brannen 682e8fb3ad Reduce code duplication in MergedSqlConfig 2014-07-18 14:39:23 +02:00
Sam Brannen 2e75adb04c Improve transaction management for @Sql scripts
Prior to this commit, the support for SQL script execution via @Sql
provided an algorithm for looking up a required
PlatformTransactionManager to use to drive transactions. However, a
transaction manager is not actually required for all testing scenarios.

This commit improves the transaction management support for @Sql so
that SQL scripts can be executed without a transaction if a transaction
manger is not present in the ApplicationContext. The updated algorithm
now supports the following use cases.

 - If a transaction manager and data source are both present (i.e.,
   explicitly specified via the transactionManager and dataSource
   attributes of @SqlConfig or implicitly discovered in the
   ApplicationContext based on conventions), both will be used.

 - If a transaction manager is not explicitly specified and not
   implicitly discovered based on conventions, SQL scripts will be
   executed without a transaction but requiring the presence of a data
   source. If a data source is not present, an exception will be thrown.

 - If a data source is not explicitly specified and not implicitly
   discovered based on conventions, an attempt will be made to retrieve
   it by using reflection to invoke a public method named
   getDataSource() on the transaction manager. If this attempt fails,
   an exception will be thrown.

 - If a data source can be retrieved from the resolved transaction
   manager using reflection, an exception will be thrown if the
   resolved data source is not the data source associated with the
   resolved transaction manager. This helps to avoid possibly
   unintended configuration errors.

 - If @SqlConfig.transactionMode is set to ISOLATED, an exception will
   be thrown if a transaction manager is not present.

Issue: SPR-11911
2014-07-18 02:59:03 +02:00
Sam Brannen dfcb2a2875 Fix test broken by previous refactoring 2014-07-16 21:51:49 +02:00
Sam Brannen 91c9bad12e Rename test classes previously related only to ContextLoaderUtils 2014-07-16 21:49:29 +02:00
Sam Brannen c290839914 Investigate claim on SO regarding ctx cache in TCF
This commit introduces a test that investigates a claim made on Stack
Overflow regarding context caching in the TestContext Framework (TCF).
2014-07-16 21:34:43 +02:00
Sam Brannen da5b0b97d3 Update Javadoc in SqlScriptsTestExecutionListener 2014-07-16 18:19:49 +02:00
Sam Brannen 5cb046da3d Update Javadoc in SqlScriptsTestExecutionListener 2014-07-16 18:16:46 +02:00
Sam Brannen a488515097 Simplify logic in MergedSqlConfig 2014-07-16 18:12:59 +02:00
Sam Brannen 6d6f008faa Polish Javadoc for MergedSqlConfig 2014-07-16 17:54:23 +02:00
Sam Brannen c1a2f5efa4 Remove unnecessary warning suppression in ModelResultMatchers 2014-07-16 17:44:44 +02:00
Sam Brannen 628806e85b Introduce @SqlConfig for common SQL script config
Prior to this commit, @Sql provided attributes for configuring the
syntax of the referenced SQL scripts as well as exception handling and
transaction behavior; however, such configuration could not be reused
across @Sql declarations thus requiring developers to copy-and-paste
common configuration and resulting in unnecessary code duplication.

This commit addresses this issue by introducing a new @SqlConfig
annotation that can be used to declare common, global configuration for
SQL scripts that can be reused within a test class hierarchy.

 - Introduced top-level @SqlConfig annotation and extracted
   common configuration attributes from @Sql.

 - @SqlConfig can be used at the class level for common, global config
   or via the new 'config' attribute of @Sql for local config.

 - Introduced MergedSqlConfig as a holder for the merged values from
   local and global @SqlConfig instances. MergedSqlConfig also contains
   the logic for overriding global configuration with local
   configuration.

 - Refactored all attributes of @SqlConfig to be either of type String
   or custom enums in order to support overriding. Empty Strings or
   DEFAULT enum values imply the use of a default or inherited value.

Issue: SPR-11896
2014-07-16 17:21:15 +02:00
Rossen Stoyanchev c2b0fac852 Add extension point to pre-configure a MockMvcBuilder
Issue: SPR-11497
2014-07-15 22:59:25 -04:00
Rossen Stoyanchev 10a4c2cd81 Remove FreeMarker/Velocity/TilesConfigurer MVC config
After some further discussion:

The MVC config simplifies ViewResolver configuration especially where
content negotiation view resolution is involved.

The configuration of the underlying view technology however is kept
completely separate. In the case of the MVC namespace, dedicated
top-level freemarker, velocity, and tiles namespace elements are
provided. In the case of the MVC Java config, applications simply
declare FreeMarkerConfigurer, VelocityConfigurer, or TilesConfigurer
beans respectively.

Issue: SPR-7093
2014-07-15 14:27:01 -04:00
Rossen Stoyanchev f54cee47b0 Update ViewResolver registration classes
Following the separation of FreeMarker/Velocity/TilesConfigurer-related
configuration via separate interface, simplify and streamline the
view registration helper classes which no longer have much difference
(most are UrlBasedViewResolver's).

Updates to Javadoc and tests.

Issue: SPR-7093
2014-07-13 22:53:23 -04:00
Rossen Stoyanchev 5bc793768c Introduce Freemarker/Velocity/TilesWebMvcConfigurer
This change improves the support for auto-registration of FreeMarker,
Velocity, and Tiles configuration.

The configuration is now conditional not only based on the classpath
but also based on whether a FreeMarkerConfigurer for example is already
present in the configuration.

This change also introduces FreeMarker~, Velocity~, and
TilesWebMvcConfigurer interfaces for customizing each view technology.

The WebMvcConfigurer can still be used to configure all view resolvers
centrally (including FreeMarker, Velocity, and Tiles) without some
default conifguration, i.e. without the need to use the new
~WebMvcConfigurer interfaces until customizations are required.

Issue: SPR-7093
2014-07-12 17:23:47 -04:00
Sebastien Deleuze cc7e8f5558 Support Java and MVC namespace view resolution config
This commit improves and completes the initial MVC namespace
view resolution implementation. ContentNegotiatingViewResolver
registration is now also supported.

Java Config view resolution support has been added.
FreeMarker, Velocity and Tiles view configurers are registered
depending on the classpath thanks to an ImportSelector.

For both, a default configuration is provided and documented.

Issue: SPR-7093
2014-07-12 17:23:47 -04:00
Lea Farmer 85cdb9196e Added field error code matching to MockMvc
This change adds a method within the ModelResultMatcher that will allow
a user to assert whether the returned Model has an attribute with a
field that has a specific error associated with it.

Issue: SPR-11971
2014-07-11 09:36:09 -04:00
Juergen Hoeller 3c726aa6c1 Polishing 2014-07-09 21:24:59 +02:00
Sam Brannen 58955236ee Introduce tests for Spring Boot issue 885
This commit introduces unit tests that attempt to reproduce the problem
described in Spring Boot issue 885; however, the tests pass and
therefore do not confirm the reported problem.

See: https://github.com/spring-projects/spring-boot/issues/885
2014-07-04 16:11:28 +02:00
Sam Brannen 0d710f197e Polishing tests in spring-test 2014-07-03 19:33:20 +02:00
Sam Brannen bdceaa481b Introduce TestNG tests for programmatic tx mgmt in the TCF
Issue: SPR-5079
2014-07-02 23:14:42 +02:00
Sam Brannen f667e43ca2 Introduce programmatic tx mgmt in the TCF
Historically, Spring's JUnit 3.8 TestCase class hierarchy supported
programmatic transaction management of "test-managed transactions" via
the protected endTransaction() and startNewTransaction() methods in
AbstractTransactionalSpringContextTests.

The Spring TestContext Framework (TCF) was introduced in Spring 2.5 to
supersede the legacy JUnit 3.8 support classes; however, prior to this
commit the TCF has not provided support for programmatically starting
or stopping the test-managed transaction.

This commit introduces a TestTransaction class in the TCF that provides
static utility methods for programmatically interacting with
test-managed transactions. Specifically, the following features are
supported by TestTransaction and its collaborators.

 - End the current test-managed transaction.

 - Start a new test-managed transaction, using the default rollback
   semantics configured via @TransactionConfiguration and @Rollback.

 - Flag the current test-managed transaction to be committed.

 - Flag the current test-managed transaction to be rolled back.

Implementation Details:

 - TransactionContext is now a top-level, package private class.

 - The existing test transaction management logic has been extracted
   from TransactionalTestExecutionListener into TransactionContext.

 - The current TransactionContext is stored in a
   NamedInheritableThreadLocal that is managed by
   TransactionContextHolder.

 - TestTransaction defines the end-user API, interacting with the
   TransactionContextHolder behind the scenes.

 - TransactionalTestExecutionListener now delegates to
   TransactionContext completely for starting and ending transactions.

Issue: SPR-5079
2014-07-02 22:52:54 +02:00
Sebastien Deleuze 9e52004222 Add support for asserting JSON
Based on the JSONassert library.

Issue: SPR-10113
2014-07-01 22:47:02 -04:00
Sam Brannen 669386abac Organize imports in Spring MVC Test classes 2014-07-01 17:57:48 +02:00
Sam Brannen 49e960c151 Polish doc & imports for MockAsyncClientHttpRequest
Issue: SPR-11822
2014-07-01 16:36:48 +02:00
Rossen Stoyanchev 9aa53abdf9 Add AsyncRestTemplate support to client-side MockMvc
Issue: SPR-1822
2014-06-28 09:49:19 -04:00
Juergen Hoeller cc917de24d Polishing 2014-06-26 11:44:07 +02:00
Sam Brannen b4e16eacc5 Require JUnit 4.9 or higher in the TCF
Prior to this commit, the Spring TestContext Framework (TCF) was
compatible with JUnit 4.5 or higher.

This commit effectively raises the minimum version of JUnit that is
officially supported by the TCF to JUnit 4.9, thereby aligning with
similar upgrades made in the Spring Framework 4.0 release (i.e.,
upgrading minimum requirements on third-party libraries to versions
released mid 2010 or later).

Issue: SPR-11908
2014-06-25 10:10:25 +02:00
Sam Brannen f1517f03ff Delete remaining SimpleJdbcTemplate usage
This commit deletes all remaining usage of the deprecated
SimpleJdbcTemplate class within the framework itself.

Issue: SPR-11895
2014-06-22 15:40:41 +02:00
Sam Brannen 0c1249fe42 Introduce repeatable @Sql tests
This commit introduces explicit integration tests that verify Java 8's
@Repeatable support for the @Sql annotation.

Issue: SPR-7655
2014-06-20 14:37:45 +02:00
Sam Brannen abdb010fc8 Rename SQL script annotations in the TCF
Prior to this commit, SQL script annotations and related classes in the
TestContext framework (TCF) were named DatabaseInitializer*. However,
these annotations are not used only for initialization and are
therefore misleading when used for cleaning up the database.

This commit refines the names of annotations and related classes for
configuring SQL scripts to be executed for integration tests in the TCF
as follows:

- @DatabaseInitializer -> @Sql
- @DatabaseInitializers -> @SqlGroup
- DatabaseInitializerTestExecutionListener -> SqlScriptsTestExecutionListener

A special thanks goes out to the following attendees of the Zurich
Hackergarten meeting last night for their collective brainstorming:
@aalmiray, @atsticks, @ollin, @simkuenzi, @tangresh, @vyazelenko.

Issue: SPR-7655
2014-06-20 14:33:23 +02:00
Rossen Stoyanchev b214db3fc8 Rename HttpStatus 308 to Permanent Redirect
Issue: SPR-11854
2014-06-10 18:51:22 -04:00
Rossen Stoyanchev c269d27bde Improve no content handling in MockHttpServletRequest
Issue: SPR-11764
2014-06-06 11:25:15 -04:00
Sam Brannen f48bdafd52 Polish Javadoc for TestContextTransactionUtils 2014-06-05 21:09:29 +02:00
Sam Brannen 5fd6ebb548 Introduce annotation to execute SQL scripts in the TCF
Prior to this commit, it was possible to execute SQL scripts
programmatically via ResourceDatabasePopulator, JdbcTestUtils, and
ScriptUtils. Furthermore, it was also possible to execute SQL scripts
declaratively via the <jdbc> XML namespace. However, it was not
possible to execute SQL scripts declaratively on a per test class or
per test method basis.

This commit makes it possible to declaratively configure SQL scripts
for execution in integration tests via annotations that can be declared
at the class or method level. Details follow.

 - Introduced a repeatable @DatabaseInitializer annotation that can be
   used to configure SQL scripts at the class or method level with
   method-level overrides. @DatabaseInitializers serves as a container
   for @DatabaseInitializer.

 - Introduced a new DatabaseInitializerTestExecutionListener that is
   responsible for parsing @DatabaseInitializer and
   @DatabaseInitializers and executing SQL scripts.

 - DatabaseInitializerTestExecutionListener is registered by default in
   abstract base test classes as well as in TestContextBootstrapper
   implementations.

 - @DatabaseInitializer and @DatabaseInitializers may be used as
   meta-annotations; however, attribute overrides are not currently
   supported for repeatable annotations used as meta-annotations. This
   is a known limitation of Spring's AnnotationUtils.

 - The semantics for locating SQL script resources is consistent with
   @ContextConfiguration's semantics for locating XML configuration
   files. In addition, a default SQL script can be detected based
   either on the name of the annotated class or on the name of the
   annotated test method.

 - @DatabaseInitializer allows for specifying which DataSource and
   PlatformTransactionManager to use from the test's
   ApplicationContext, including default conventions consistent with
   TransactionalTestExecutionListener and @TransactionConfiguration.

 - @DatabaseInitializer supports all of the script configuration options
   currently supported by ResourceDatabasePopulator.

 - @DatabaseInitializer and DatabaseInitializerTestExecutionListener
   support execution phases for scripts that dictate when SQL scripts
   are executed (i.e., before or after a test method).

 - SQL scripts can be executed within the current test's transaction if
   present, outside of the current test's transaction if present, or
   always in a new transaction, depending on the value of the boolean
   requireNewTransaction flag in @DatabaseInitializer.

 - DatabaseInitializerTestExecutionListener delegates to
   ResourceDatabasePopulator#execute to actually execute the scripts.

Issue: SPR-7655
2014-06-05 20:06:11 +02:00
Juergen Hoeller 5eecb138f6 Unit tests for custom profile annotations on configuration classes
Issue: SPR-11808
2014-05-30 22:04:40 +02:00
Sam Brannen 4b291c665c Upgrade spring-test tests to Hibernate 4
This commit upgrades Hibernate-based integration tests in the
spring-test module to use Hibernate 4 instead of 3 and Hibernate
Validator 5 instead of 4. This streamlines and simplifies our
dependency management at the same time.

Issue: SPR-11834
2014-05-29 18:18:55 +02:00
Juergen Hoeller d9b39ad691 Consistent use of IllegalStateException instead of InternalError for UnsupportedEncodingException cause 2014-05-20 00:37:09 +02:00
Juergen Hoeller 1285467fe6 Consistently log Class.getName() instead of Class.toString(), avoiding double class term in log message
Issue: SPR-11804
2014-05-19 22:29:10 +02:00
Juergen Hoeller 2619955fc3 Consistently log Class.getName() instead of Class.toString(), avoiding double class term in log message
Issue: SPR-11804
2014-05-19 20:18:50 +02:00
Juergen Hoeller 41ed228450 Refined check for NoClassDefFoundError in getTestExecutionListeners()
Issue: SPR-11804
2014-05-19 16:31:23 +02:00
Rossen Stoyanchev 676282c66e Support ListenableFuture on @RequestMapping methods
Issue: SPR-11695
2014-05-01 12:28:59 -04:00
Juergen Hoeller 02aca9c754 Polishing 2014-04-30 00:01:07 +02:00
Juergen Hoeller 6cb45f714e General defensiveness about the bootstrap ClassLoader (i.e. null ClassLoader)
Issue: SPR-11721
(cherry picked from commit 59cef3c)
2014-04-28 00:47:21 +02:00
Alex Panchenko 09341b996e Add space separator in JsonPathExpectationsHelper 2014-04-25 18:04:54 +07:00
Stephane Nicoll 5559209233 Remove useless imports 2014-04-22 09:57:12 +02:00
Sam Brannen ba3c7e588f Polish Javadoc for SpringJUnit4ClassRunner 2014-04-10 18:28:36 +02:00
Sam Brannen 1bbc55d63c Polish Javadoc for TestContextBootstrapper 2014-04-10 01:09:51 +02:00
Sam Brannen 5df60a2bec Update ContextLoaderUtils Javadoc due to recent refactoring 2014-04-10 00:56:23 +02:00
Sam Brannen e1a1e1205f Simplify DefaultBootstrapContext.toString() 2014-04-10 00:44:14 +02:00
Sam Brannen a281bdbfc5 Introduce context bootstrap strategy in the TCF
Work done in conjunction with SPR-5243 and SPR-4588 introduced physical
package cycles in the spring-test module. The work performed in
conjunction with SPR-9924 uses reflection to resolve these physical
package cycles; however, prior to this commit the logical package
cycles still remain.

Furthermore, over time it has become apparent that the Spring
TestContext Framework (TCF) could better serve application developers
and especially third-party framework developers by providing a more
flexible mechanism for "bootstrapping" the TCF. For example, prior to
this commit, default TestExecutionListeners could only be registered by
subclassing TestContextManager (and SpringJUnit4ClassRunner if using
JUnit). Similarly, the default ContextLoader could only be set by
subclassing SpringJUnit4ClassRunner for JUnit and by copying and
modifying AbstractTestNGSpringContextTests for TestNG.

This commit addresses the aforementioned issues by introducing a
bootstrap strategy in the TestContext framework that is responsible for
determining default TestExecutionListeners and the default
ContextLoader in an extensible fashion. The new TestContextBootstrapper
SPI also provides a mechanism for supporting various types of
MergedContextConfiguration depending on the feature set of the context
loaders supported by the strategy.

The following provides an overview of the most significant changes in
this commit.

 - Introduced TestContextBootstrapper strategy SPI, BootstrapContext,
   and @BootstrapWith.

 - Introduced AbstractTestContextBootstrapper,
   DefaultTestContextBootstrapper, and WebTestContextBootstrapper
   implementations of the TestContextBootstrapper SPI and extracted
   related reflection code from ContextLoaderUtils & TestContextManager.

 - Introduced BootstrapUtils for retrieving the TestContextBootstrapper
   from @BootstrapWith, falling back to a default if @BootstrapWith is
   not present.

 - @WebAppConfiguration is now annotated with
   @BootstrapWith(WebTestContextBootstrapper.class).

 - CacheAwareContextLoaderDelegate is now an interface with a new
   DefaultCacheAwareContextLoaderDelegate implementation class.

 - Introduced closeContext(MergedContextConfiguration, HierarchyMode) in
   CacheAwareContextLoaderDelegate.

 - DefaultTestContext now uses CacheAwareContextLoaderDelegate instead
   of interacting directly with the ContextCache.

 - DefaultTestContext now delegates to a TestContextBootstrapper for
   building the MergedContextConfiguration.

 - TestContextManager now delegates to TestContextBootstrapper for
   retrieving TestExecutionListeners.

 - Deleted TestContextManager(Class, String) constructor and
   SpringJUnit4ClassRunner.getDefaultContextLoaderClassName(Class)
   method since default ContextLoader support is now implemented by
   TestContextBootstrappers.

 - Extracted ActiveProfilesUtils from ContextLoaderUtils.

 - Extracted ApplicationContextInitializerUtils from ContextLoaderUtils.

 - MetaAnnotationUtils is now a public utility class in the test.util
   package.

 - Removed restriction in @ActiveProfiles that a custom resolver cannot
   be used with the 'value' or 'profiles' attributes.

 - Introduced DefaultActiveProfilesResolver.

Issue: SPR-9955
2014-04-10 00:15:34 +02:00
Sam Brannen d53b498839 Don't encode '@' in {@code} tags 2014-04-08 15:01:54 +02:00
Sam Brannen a1486e46c8 Don't encode '@' in {@code} tags 2014-04-08 14:36:49 +02:00
Sam Brannen 4cd075bb96 Introduce test for PropertySource + ACI in the TCF
This commit introduces an explicit integration test to verify that a
PropertySource can be set via a custom ApplicationContextInitializer in
the Spring TestContext Framework.

Issue: SPR-11666
2014-04-06 20:09:22 +02:00
Sam Brannen 89a4c291c3 Remove trailing whitespace 2014-04-01 20:22:25 +02:00
Sam Brannen 1f017c4acb Support classes AND locations in @ContextConfiguration
Prior to this commit, the Spring TestContext Framework did not support
the declaration of both 'locations' and 'classes' within
@ContextConfiguration at the same time.

This commit addresses this in the following manner:

 - ContextConfigurationAttributes no longer throws an
   IllegalArgumentException if both 'locations' and 'classes' are
   supplied to its constructor.

 - Concrete SmartContextLoader implementations now validate the
   supplied MergedContextConfiguration before attempting to load the
   ApplicationContext. See validateMergedContextConfiguration().

 - Introduced tests for hybrid context loaders like the one used in
   Spring Boot. See HybridContextLoaderTests.

 - Updated the Testing chapter of the reference manual so that it no
   longer states that locations and classes cannot be used
   simultaneously, mentioning Spring Boot as well.

 - The Javadoc for @ContextConfiguration has been updated accordingly.

 - Added hasLocations(), hasClasses(), and hasResources() convenience
   methods to MergedContextConfiguration.

Issue: SPR-11634
2014-04-01 19:45:56 +02:00
Sam Brannen 5d049e0de8 Introduce execute(DataSource) in ResrcDbPopulator
To simplify common use cases, this commit introduces a new
execute(DataSource) method in ResourceDatabasePopulator that complements
the existing populate(Connection) method.

Issue: SPR-11629
2014-03-30 17:01:48 +02:00
Sam Brannen c38600762d Reinject Servlet mocks between TestNG test methods
Prior to this commit, if multiple test methods were executed in a
subclass of AbstractTestNGSpringContextTests annotated with
@WebAppConfiguration, then injected Servlet API mocks would only
reference the mocks created for the first test method. Subsequent test
methods could therefore never reference the current mocks, and there
was a discrepancy between the state of the injected mocks and the mock
set in the RequestContextHolder.

This commit addresses this issue by ensuring that dependencies
(including updated mocks) are injected into the test instance before
the next test method if the ServletTestExecutionListener resets the
request attributes in RequestContextHolder.

Issue: SPR-11626
2014-03-29 21:14:49 +01:00
Sam Brannen 5c577451f3 Polish Javadoc in abstract base test classes in the TCF 2014-03-27 14:49:26 +01:00
Juergen Hoeller dd7f54c3c0 Revised ResizableByteArrayOutputStream as an actual subclass of ByteArrayOutputStream, and consistently applied appropriate ByteArrayOutputStream initial capacities across the codebase
Issue: SPR-11594
2014-03-24 22:57:38 +01:00
Rossen Stoyanchev 05213c684c Give meaningful names to SprXxxTests in spring-test 2014-03-24 10:01:35 -04:00
Rossen Stoyanchev 9bda734e0a Improve method order in MockMvcRequestBuilders 2014-03-24 10:01:35 -04:00
Sebastien Deleuze 0b69a0ba4b Add URI based MockHttpServletRequestBuilder constructors
This commit adds new MockHttpServletRequestBuilder constructors
with an URI parameter in addition to the URL template + URL variables
existing ones.

It gives more control on how the URL is built, allowing for example to
use URL variables containing '/' character with proper encoding.

Issue: SPR-11441
2014-03-24 10:01:35 -04:00
Stephane Nicoll 4cd818b9e4 Harmonize log configuration
Prior to this commit, the codebase was using a mix of log4j.xml
and log4j.properties for test-related logging configuration. This
can be an issue as log4j takes the xml variant first when looking
for a default bootstrap configuration.

In practice, some modules declaring the properties variant were
taking the xml variant configuration from another module.

The general structure of the configuration has also been
harmonized to provide a standard console output as well as an
easy way to enable trace logs for the current module.
2014-03-20 09:43:29 -07:00
Sam Brannen 14a8f19670 Add links to class-level Javadoc in JdbcTestUtils 2014-03-16 17:44:11 +01:00
Sam Brannen 01b2f67f11 Introduce constructors in ResourceDatabasePopulator
Issue: SPR-9531
2014-03-13 13:45:05 +01:00
Sam Brannen a006ca2542 Remove trailing whitespace 2014-03-13 12:21:32 +01:00
Sam Brannen 2bfd6ddcf4 Refactor SQL script support
This commit continues the work in the previous commit as follows:

 - Introduced an exception hierarchy for exceptions related to SQL
   scripts, with ScriptException as the base.

 - CannotReadScriptException and ScriptStatementFailedException now
   extend ScriptException.

 - Introduced ScriptParseException, used by ScriptUtils.splitSqlScript().

 - DatabasePopulatorUtils.execute() now explicitly throws a
   DataAccessException.

 - Polished Javadoc in ResourceDatabasePopulator.

 - Overhauled Javadoc in ScriptUtils and documented all constants.

 - Added missing @author tags for original authors in ScriptUtils and
   ScriptUtilsTests.

 - ScriptUtils.splitSqlScript() now asserts preconditions.

 - Deleted superfluous methods in ScriptUtils and changed method
   visibility to private or package private as appropriate.

 - Deleted the ScriptStatementExecutor introduced in the previous
   commit; ScriptUtils.executeSqlScript() now accepts a JDBC Connection;
   JdbcTestUtils, AbstractTransactionalJUnit4SpringContextTests, and
   AbstractTransactionalTestNGSpringContextTests now use
   DatabasePopulatorUtils to execute a ResourceDatabasePopulator instead
   of executing a script directly via ScriptUtils.

 - Introduced JdbcTestUtilsIntegrationTests.

Issue: SPR-9531
2014-03-13 12:00:01 +01:00
cbaldwin74 e5c17560db Support multi-line comments in SQL scripts
Prior to this commit neither ResourceDatabasePopulator nor
JdbcTestUtils properly supported multi-line comments (e.g., /* ... */).
Secondarily there has developed a significant amount of code
duplication in these two classes that has led to maintenance issues
over the years.

This commit addresses these issues as follows:

 - Common code has been extracted from ResourceDatabasePopulator and
   JdbcTestUtils and moved to a new ScriptUtils class in the
   spring-jdbc module.

 - Relevant test cases have been migrated from JdbcTestUtilsTests to
   ScriptUtilsTests.

 - ScriptUtils.splitSqlScript() has been modified to ignore multi-line
   comments in scripts during processing.

 - ResourceDatabasePopulator supports configuration of the start and end
   delimiters for multi-line (block) comments.

 - A new test case was added to ScriptUtilsTests for the new multi-line
   comment support.

Issue: SPR-9531
2014-03-13 10:51:08 +01:00
Rossen Stoyanchev 6a4a2ec6a4 Fix expected and actual argument order
Issue: SPR-11424
2014-03-12 16:52:52 -04:00
Sam Brannen b364599278 Update links to Spring JIRA server 2014-03-10 12:26:29 +01:00
Sam Brannen 1d57a15e40 Delete unused imports in spring-test 2014-03-07 18:27:34 +01:00
Sam Brannen cb59d43a5f Fix typos in Javadoc in AssertThrows 2014-03-06 14:40:41 +01:00
Sam Brannen cf3b2b1a4d Simplify test includes & excludes in Gradle build
This commit aligns our include and exclude filters for test classes
with Gradle's standard patterns. Specifically, our patterns now end
with ".class" instead of ".*".

The aforementioned change makes the exclusion of inner classes
unnecessary. Thus, patterns for test classes ending with "TestCase" or
"TestSuite" have been deleted.

Furthermore, the include and exclude patterns previously used in the
spring-test module made it impossible for the
FailingBeforeAndAfterMethodsTests class in the 'testng' package to ever
be executed by the build. This has been addressed by renaming our JUnit
and TestNG variants of FailingBeforeAndAfterMethodsTests and moving the
TestNG variant into the 'junit' package so that it can be picked with
our standard include pattern for JUnit-based tests.
2014-03-06 00:06:50 +01:00
Rossen Stoyanchev 34924810fe Remove field no longer used after previous commit
Issue: SPR-11516
2014-03-05 14:50:16 -05:00
Rossen Stoyanchev 74de35df1e Refactor async result handling in Spring MVC Test
This change removes the use of a CountDownLatch to wait for the
asynchronously computed controller method return value. Instead we
check in a loop every 200 milliseconds if the result has been set.
If the result is not set within the specified amount of time to wait
an IllegalStateException is raised.

Additional changes:
 - Use AtomicReference to hold the async result
 - Remove @Ignore annotations on AsyncTests methods
 - Remove checks for the presence of Servlet 3

Issue: SPR-11516
2014-03-05 12:55:39 -05:00
Rossen Stoyanchev 705efc5bdf Fix timing issue with obtaining async result
Issue: SPR-11516
2014-03-04 21:38:42 -05:00
Rossen Stoyanchev c553d681f1 Add Servlet 3.1 methods to mock request
Issue: SPR-11492
2014-02-28 12:28:17 -05:00
Sam Brannen 979c483384 Do not inspect meta-annotations on Java annotations
This commit introduces a new isInJavaLangAnnotationPackage(Annotation)
method in AnnotationUtils. This method is now used in AnnotationUtils,
AnnotatedElementUtils, and MetaAnnotationUtils to ensure that search
algorithms do no search for meta-annotations on annotations in the
"java.lang.annotation" package.

The following are some empirical results from this change:

- The number of times that the findAnnotation(Class,Class,Set) method in
  AnnotationUtils is recursively invoked while executing
  AnnotationUtilsTests drops from 51 to 29.

- The number of times that the process(AnnotatedElement) method in
  AnnotationUtils.AnnotationCollector is recursively invoked while
  executing AnnotationUtilsTests.getRepeatableFromMethod() drops
  from 16 to 2.

- The number of times that the doProcess() method in
  AnnotatedElementUtils is recursively invoked while executing the
  "getAnnotationAttributes() On MetaCycleAnnotatedClass with missing
  target meta-annotation" test in AnnotatedElementUtilsTests drops
  from 23 to 5.

- The number of times that the findAnnotationDescriptor(Class,Set,Class)
  method in MetaAnnotationUtils is recursively invoked while executing
  the "findAnnotationDescriptor() on MetaCycleAnnotatedClass with
  missing target meta-annotation" test in MetaAnnotationUtilsTests drops
  from 16 to 8.

Issue: SPR-11483
2014-02-25 21:57:35 +01:00
Sam Brannen 78b69f5d77 Always supply test class to ContextLoaders in TCF
Prior to this commit, the following methods in ContextLoaderUtils
treated a composed @ContextConfiguration annotation (i.e., a custom
annotation that is meta-annotated with @ContextConfiguration) as the
"declaring class" instead of the actual test class.

- resolveContextConfigurationAttributes()
- resolveContextHierarchyAttributes()

As a consequence, if @ContextConfiguration is used as a
meta-annotation, the meta-annotated class is stored as the
"declaringClass" in ContextConfigurationAttributes. Thus, when a
ContextLoader (or SmartContextLoader) attempts to detect default
resource locations or configuration classes, it does so for the
composed annotation class instead of for the declaring test class.

This commit ensures that ContextLoaders are supplied the declaring test
class instead of the composed annotation class in such use cases.

Issue: SPR-11455
2014-02-25 15:27:31 +01:00
Sam Brannen f8950960f2 Support arbitrary meta-annotation levels in the TCF
Prior to this commit, the findAnnotationDescriptor() and
findAnnotationDescriptorForTypes() methods in MetaAnnotationUtils only
supported a single level of meta-annotations. In particular, this kept
the following annotations from being used as meta-annotations on
meta-annotations:

- @ContextConfiguration
- @ContextHierarchy
- @ActiveProfiles
- @TestExecutionListeners

This commit alters the search algorithms used in MetaAnnotationUtils so
that arbitrary levels of meta-annotations are now supported for the
aforementioned test-related annotations.

Issue: SPR-11470
2014-02-23 01:05:15 +01:00
Sam Brannen 2c8f25a14c Delete call to System.err in AbstractContextLoaderUtilsTests 2014-02-23 00:28:00 +01:00
Sam Brannen aa3e250ab6 @Ignore PrintingResultHandlerTests 2014-02-23 00:24:24 +01:00
Sam Brannen 3c511f00cc Simplify MetaAnnotationUtilsTests 2014-02-22 18:48:55 +01:00
Sam Brannen d9a2b3c2ba Deleted unused code in ContextLoaderUtilsActiveProfilesTests 2014-02-22 18:09:59 +01:00
Sam Brannen dc6eaad2e9 Update copyright date in ContextLoaderUtils 2014-02-22 18:06:37 +01:00