Commit Graph

3081 Commits

Author SHA1 Message Date
Sam Brannen 2137750591 Improve Bean Override by-name integration tests 2024-12-09 13:01:42 +01:00
Sam Brannen 2015a93823 Merge branch '6.2.x' 2024-12-08 18:41:37 +01:00
Sam Brannen aee52b53a1 Introduce MockitoAssertions 2024-12-08 18:41:10 +01:00
Sam Brannen 92bbaa21e0 Improve test coverage for @⁠MockitoSpyBean use cases 2024-12-08 18:41:10 +01:00
Sam Brannen 0e50fe4f6a Merge branch '6.2.x' 2024-12-07 16:56:23 +01:00
Sam Brannen aa7b459803 Fix Phantom Read problem for Bean Overrides in the TestContext framework
To make an analogy to read phenomena for transactional databases, this
commit effectively fixes the "Phantom Read" problem for Bean Overrides.

A phantom read occurs when the BeanOverrideBeanFactoryPostProcessor
retrieves a set of bean names by-type twice and a new bean definition
for a compatible type has been created in the BeanFactory by a
BeanOverrideHandler between the first and second retrieval.

Continue reading for the details...

Prior to this commit, the injection of test Bean Overrides (for
example, when using @⁠MockitoBean) could fail in certain scenarios if
overrides were created for nonexistent beans "by type" without an
explicit name or qualifier. Specifically, if an override for a SubType
was created first, and subsequently an attempt was made to create an
override for a SuperType (where SubType extends SuperType), the
override for the SuperType would "override the override" for the
SubType, effectively removing the override for the SubType.
Consequently, injection of the override instance into the SubType field
would fail with an error message similar to the following.

BeanNotOfRequiredTypeException: Bean named 'Subtype#0' is expected to
be of type 'Subtype' but was actually of type 'Supertype$Mock$XHb7Aspo'

This commit addresses this issue by tracking all generated bean names
(in a generatedBeanNames set) and ensuring that a new bean override
instance is created for the current BeanOverrideHandler if a previous
BeanOverrideHandler already created a bean override instance that now
matches the type required by the current BeanOverrideHandler.

In other words, if the generatedBeanNames set already contains the
beanName that we just found by-type, we cannot "override the override",
because we would lose one of the overrides. Instead, we must create a
new override for the current handler. In the example given above, we
must end up with overrides for both SuperType and SubType.

Closes gh-34025
2024-12-07 16:51:16 +01:00
Sam Brannen 03fe1f0df3 Improve documentation for BeanOverrideBeanFactoryPostProcessor 2024-12-07 16:05:54 +01:00
Juergen Hoeller 162e533393 Merge branch '6.2.x'
# Conflicts:
#	spring-context/src/test/java/org/springframework/scheduling/concurrent/AbstractSchedulingTaskExecutorTests.java
#	spring-web/src/main/java/org/springframework/http/MediaType.java
#	spring-websocket/spring-websocket.gradle
#	spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java
#	spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/DefaultTransportRequest.java
2024-12-04 16:45:54 +01:00
Juergen Hoeller edf7f3cd43 Polishing 2024-12-04 16:41:07 +01:00
Juergen Hoeller 2b9010c2a2 Remove APIs marked as deprecated for removal
Closes gh-33809
2024-12-04 13:19:39 +01:00
Sam Brannen d41d674c4f Update code due to upgrade to Jakarta EE 11 APIs 2024-12-03 15:10:32 +01:00
Juergen Hoeller 949432ce8b General upgrade to Jakarta EE 11 APIs
Includes removal of ManagedBean and javax.annotation legacy support.
Includes AbstractJson(Http)MessageConverter revision for Yasson 3.0.
Includes initial Hibernate ORM 7.0 upgrade.

Closes gh-34011
Closes gh-33750
2024-12-03 13:30:25 +01:00
Brian Clozel ba312f6c7c Update AOT support after RuntimeHints changes
This commit adapts AOT support in various modules after the RuntimeHints
and related deprecation changes.

`MemberCategory.INTROSPECT_*` hints are now removed and
`MemberCategory.*_FIELDS` are  replaced with
`MemberCategory.INVOKE*_FIELDS` when invocation is needed.

Usage of `RuntimeHintsAgent` are also deprecated.

Closes gh-33847
2024-11-29 14:44:05 +01:00
Sam Brannen bd81abe58d Merge branch '6.2.x' 2024-11-29 11:32:53 +01:00
Sam Brannen 51956fad89 Test MockReset strategy for @⁠MockitoSpyBean
As a follow up to commit 0088b9c7f8, this commit introduces an
integration test which verifies that a spy created via @⁠MockitoSpyBean
using the MockReset.AFTER strategy is not reset between the refresh of
the ApplicationContext and the first use of the spy within a @⁠Test
method.

See gh-33941
See gh-33986
2024-11-29 11:27:02 +01:00
Sam Brannen 98676746f3 Merge branch '6.2.x' 2024-11-26 11:58:44 +01:00
Sam Brannen 0088b9c7f8 Honor MockReset strategy for @⁠MockitoBean and @⁠MockitoSpyBean
Commit 6c2cba5d8a introduced a regression by inadvertently removing the
MockReset strategy comparison when resetting @⁠MockitoBean and
@⁠MockitoSpyBean mocks.

This commit reinstates the MockReset strategy check and introduces
tests for this feature.

Closes gh-33941
2024-11-26 11:54:46 +01:00
Brian Clozel 5e08a88219 Upgrade Servlet mock classes to Servlet 6.1
This commit upgrades our Mock Servlet classes for Servlet 6.1 support:

* the read/write `ByteBuffer` variants for `ServletInputStream` and
  `ServletOutputStream` were not added as the default implementation
  matches well the testing use case.
* Implement the session accessor with a simple lambda. Our mocks do not
  simulate the scheduling of request/response processing on different
  threads.
* Ensure that the response content length can only be written before the
  response is committed. Calling those methods after commit is a no-op,
  per specification.

Closes gh-33749
2024-11-22 17:07:44 +01:00
Sam Brannen 74c48d8132 Merge branch '6.2.x' 2024-11-21 11:34:55 +01:00
Sam Brannen b9cf03f8f0 Construct consistent error messages in BeanOverrideBeanFactoryPostProcessor 2024-11-21 11:28:31 +01:00
Sam Brannen ff5529bbae Merge branch '6.2.x' 2024-11-21 09:53:46 +01:00
Sam Brannen 08a789cee9 Honor @⁠Fallback semantics for Test Bean Overrides
Closes gh-33924
2024-11-21 09:50:17 +01:00
Sam Brannen 082a8cfae3 Merge branch '6.2.x' 2024-11-20 16:51:30 +01:00
Sam Brannen 7a6e401d17 Document visibility requirements for Bean Overrides
This commit makes it clear that there are no visibility requirements
for @⁠TestBean fields or factory methods as well as @⁠MockitoBean or
@⁠MockitoSpyBean fields.

Closes gh-33923
2024-11-20 16:49:52 +01:00
Sam Brannen ba4105d4f0 Merge branch '6.2.x' 2024-11-20 11:30:48 +01:00
Sam Brannen 3569cfe990 Reject static Bean Override fields for @⁠MockitoBean, @⁠TestBean, etc.
Closes gh-33922
2024-11-20 11:29:01 +01:00
Brian Clozel c28cbfd582 Upgrade Servlet, JSP and WebSocket API versions
This commit updates the Spring Framework baseline for the Servlet, JSP
and WebSocket APIs.
This also removes the previously deprecated APIs in JSP `PageContext`
and guards against the deprecation of the `PushBuilder` API.

See gh-33918
2024-11-19 18:11:18 +01:00
Sam Brannen a3c132c442 Polish XmlExpectationsHelper[Tests] 2024-11-19 13:33:20 +01:00
boiarshinov 91791c1756 Fail with full description for XML diff in XmlExpectationsHelper
Closes gh-33827
2024-11-19 13:23:58 +01:00
Hejow 4697ae10ee Relax the visibility of MockMVC DSL constructors
Closes gh-33778
2024-11-06 10:28:15 +01:00
Sam Brannen a3b979c5ec Register runtime hints for @⁠TestBean fully-qualified method names
This commit introduces a TestBeanReflectiveProcessor that registers
GraalVM native image reflection hints for a fully-qualified method name
configured via @⁠TestBean.

Closes gh-33836
2024-11-01 16:48:06 +01:00
Sam Brannen a8f5848a5d Add missing runtime hint assertions for Bean Overrides 2024-11-01 16:47:36 +01:00
Sam Brannen 97f23dca22 Remove extra "Bean" from TestBeanBeanOverrideHandler class name
The extra "Bean" was accidentally added in commit ebdf6dc2fc.

See gh-33702
2024-11-01 14:57:30 +01:00
Sam Brannen 86784b61cc Introduce support for a custom reason in @⁠DisabledInAotMode
Closes gh-33833
2024-11-01 12:24:53 +01:00
Sam Brannen ba692aa3ef Honor MockReset without @⁠MockitoBean or @⁠MockitoSpyBean fields
Prior to this commit, the static factory methods in MockReset (such as
MockReset.before() and MockReset.after()) could only be applied to
beans within the ApplicationContext if the test class declared at least
one field annotated with either @⁠MockitoBean or @⁠MockitoSpyBean.

However, the Javadoc states that it should be possible to apply
MockReset directly to any mock in the ApplicationContext using the
static methods in MockReset.

To address that, this commit reworks the "enabled" logic in
MockitoResetTestExecutionListener as follows.

- We no longer check for the presence of annotations from the
  org.springframework.test.context.bean.override.mockito package to
  determine if MockReset is enabled.

- Instead, we now rely on a new isEnabled() method to determine if
  MockReset is enabled.

The logic in the isEnabled() method still relies on the mockitoPresent
flag as an initial check; however, mockitoPresent only determines if
Mockito is present in the classpath. It does not determine if Mockito
can actually be used. For example, it does not detect if the necessary
reachability metadata has been registered to use Mockito within a
GraalVM native image.

To address that last point, the isEnabled() method performs an
additional check to determine if Mockito can be used in the current
environment. Specifically, it invokes Mockito.mockingDetails().isMock()
which in turn initializes core Mockito classes without actually
attempting to create a mock. If that fails, that means that Mockito
cannot actually be used in the current environment, which typically
indicates that GraalVM reachability metadata has not been registered
for the org.mockito.plugins.MockMaker in use (such as the
ProxyMockMaker).

In addition, isEnabled() lazily determines if Mockito can be
initialized, since attempting to detect that during static
initialization results in a GraalVM native image error stating that
Mockito internals were "unintentionally initialized at build time".

If Mockito cannot be initialized, MockitoResetTestExecutionListener
logs a DEBUG level message providing access to the corresponding stack
trace, and MockReset support is disabled.

Closes gh-33829
2024-10-31 15:56:54 +01:00
Sam Brannen 0846706688 Adapt copyright headers copied from Spring Boot 2024-10-31 15:33:50 +01:00
Sam Brannen 4a0edc59cc Verify support for MockReset for beans within the ApplicationContext
This commit verifies that MockReset.before() and MockReset.after() are
supported for beans within the ApplicationContext.

However, the test class must declare a field annotated with either
@⁠MockitoBean or @⁠MockitoSpyBean in order for the MockReset feature to
be triggered.

See gh-33742
2024-10-30 17:31:15 +01:00
Sam Brannen e23c8bfbb6 Polishing 2024-10-30 15:56:19 +01:00
Sam Brannen 08e0baac94 Honor @⁠Primary for test Bean Overrides such as @⁠MockitoBean
Spring Boot has honored @⁠Primary for selecting which candidate bean
@⁠MockBean and @⁠SpyBean should mock or spy since Spring Boot 1.4.3;
however, the support for @⁠Primary was not ported from Spring Boot to
Spring Framework's new Bean Overrides feature in the TestContext
framework.

To address that, this commit introduces support for @⁠Primary for
selecting bean overrides -- for example, for annotations such as
@⁠TestBean, @⁠MockitoBean, and @⁠MockitoSpyBean.

See https://github.com/spring-projects/spring-boot/issues/7621
Closes gh-33819
2024-10-30 15:49:16 +01:00
Sam Brannen f427ac383d (Re)suppress deprecation warnings
See gh-33780
2024-10-30 10:52:01 +01:00
Sam Brannen c0c41ddda5 Disable unsupported tests in AOT mode as well 2024-10-30 10:29:02 +01:00
Sam Brannen 7148b28b2b Integration test Bean Override support for multiple candidate beans
This commit introduces integration tests which verify that Bean
Overrides (for example, @⁠MockitoBean and @⁠MockitoSpyBean) can select
a single candidate bean to override when there are multiple candidates
that match the required type.

To "select" the desired bean, these tests rely on one of the following.

- explicit bean name in the bean override annotation

- explicit @⁠Qualifier on the bean override field

- explicit @⁠Primary on one of the candidate beans

However, the @⁠Primary tests are currently @⁠Disabled until @⁠Primary
is honored in the Spring TestContext Framework.

See gh-33742
2024-10-30 10:22:19 +01:00
Sam Brannen c2c6bb25c6 Use BeanFactory to get type produced by a FactoryBean for Bean Overrides
Previously, we only looked at the OBJECT_TYPE_ATTRIBUTE on a
FactoryBean's bean definition; however this does not work for
situations where the information is provided by the definition's target
type rather than the attribute.

Rather than manually considering the target type in addition to the
existing consideration of the attribute, we now ask the BeanFactory for
the type that will be produced by the FactoryBean instead.

See https://github.com/spring-projects/spring-boot/issues/40234
Closes gh-33811

Co-authored-by: Andy Wilkinson <andy.wilkinson@broadcom.com>
2024-10-29 14:21:18 +01:00
Sam Brannen 40960fa85a Verify @⁠MockitoSpyBean can spy bean from FactoryBean with generics
This commit introduces a test which verifies that @⁠MockitoSpyBean on a
field with generics can be used to replace an existing bean with
matching generics that's produced by a FactoryBean that's
programmatically registered via an ImportBeanDefinitionRegistrar.

However, the test is currently @⁠Disabled until the fix for
https://github.com/spring-projects/spring-boot/issues/40234 has been
ported to Spring Framework.

See gh-33742
2024-10-29 13:55:22 +01:00
Sam Brannen 578928de39 Introduce test for Bean Override for "broken" FactoryBean
See gh-33800
2024-10-29 10:56:23 +01:00
Sam Brannen de2c10abcd Sync Javadoc for @⁠TestBean & @⁠MockitoBean with reference manual
See gh-33701
2024-10-28 12:58:33 +01:00
Sam Brannen 81d89f478a Relax singleton enforcement for Bean Overrides in the TestContext framework
In gh-33602, we introduced strict singleton enforcement for bean
overrides -- for example, for @⁠MockitoBean, @⁠TestBean, etc. However,
the use of BeanFactory#isSingleton(beanName) can result in a
BeanCreationException for certain beans, such as a Spring Data JPA
FactoryBean for a JpaRepository.

In light of that, this commit relaxes the singleton enforcement in
BeanOverrideBeanFactoryPostProcessor by only checking the result of
BeanDefinition#isSingleton() for existing bean definitions.

This commit also updates the Javadoc and reference documentation to
reflect the status quo.

See gh-33602
Closes gh-33800
2024-10-28 12:45:05 +01:00
Sam Brannen d1d6ff8737 Verify @⁠MockitoSpyBean can be used with circular dependencies
See gh-33742
2024-10-24 16:53:26 +02:00
Sam Brannen 3cc76ef87c Polishing 2024-10-24 15:47:16 +02:00
Sam Brannen 0221471265 Verify @⁠Mockito[Spy]Bean can mock/spy parameterized types
See gh-33742
2024-10-24 15:45:28 +02:00
Sam Brannen 3b82733e1f Support @⁠Mockito[Spy]Bean & @⁠TestBean w/ @⁠DirtiesContext "before method" modes
Closes gh-33783
2024-10-24 15:06:03 +02:00
Sam Brannen ba8024d077 Verify @⁠MockitoBean can be used with generics and parameterized types
See gh-33742
2024-10-24 12:48:24 +02:00
Sam Brannen efda3f0f99 Reorganize Mockito integration tests 2024-10-24 12:21:58 +02:00
Sam Brannen 761850816c Verify @⁠MockitoBean can be used with JUnit 4 and SpringMethodRule
See gh-33742
2024-10-24 12:21:58 +02:00
Sam Brannen 2d028c39b4 Align with naming in ReflectionTestUtils 2024-10-24 10:25:18 +02:00
Juergen Hoeller fe6d9145e5 Avoid hard dependency on Spring AOP for mock resolution
Closes gh-33774
2024-10-23 21:26:06 +02:00
Sam Brannen 8fa99dcbdd Polishing 2024-10-23 17:16:41 +02:00
Sam Brannen 5bf179b851 Remove proxyTargetAware attribute from @⁠MockitoSpyBean
This commit removes the proxyTargetAware attribute from @⁠MockitoSpyBean
while keeping the underlying feature in tact (i.e., transparent
verification for spies created via @⁠MockitoSpyBean).

Closes gh-33775
2024-10-23 16:39:01 +02:00
Sam Brannen d8a6423c0c Support transparent verification for @⁠MockitoSpyBean
Prior to this commit, SpringAopBypassingVerificationStartedListener
provided partial support for transparent verification for Mockito spies
created via @⁠MockitoSpyBean when the spy is wrapped in a Spring AOP
proxy. However, attempting to actually verify invocations for a spy
resulted in an exception from Mockito since MockUtil.isMock() returned
false in such scenarios.

This commit addresses that by introducing a SpringMockResolver that
resolves mocks by walking the Spring AOP proxy chain until the target
or a non-static proxy is found.

SpringMockResolver is automatically registered whenever the spring-test
JAR is on the classpath, allowing Mockito to transparently resolve mocks
wrapped in Spring AOP proxies.

Closes gh-33774
2024-10-23 15:51:35 +02:00
Sam Brannen c85689b308 Polishing 2024-10-23 14:01:52 +02:00
Sam Brannen 982f7f8f58 Verify @⁠MockitoBean & @⁠MockitoSpyBean can be used Spring AOP proxies
Use cases not yet supported with @⁠MockitoSpyBean are currently @⁠Disabled.

See gh-33742
2024-10-23 13:54:11 +02:00
Sam Brannen 23f19a0fad Add link to existing bug report 2024-10-19 13:06:21 +02:00
Sam Brannen 14c476bd42 Verify @⁠MockitoBean can replace Spring AOP advised beans
See gh-33742
2024-10-18 17:53:44 +02:00
Sam Brannen a8b36f7ad5 Verify @⁠MockitoBean can replace beans that have @⁠Async methods
See gh-33742
2024-10-18 17:38:02 +02:00
Sam Brannen d5e334339a Verify @⁠MockitoBean can replace a scoped-proxy
See gh-33742
2024-10-18 17:14:59 +02:00
Sam Brannen c0ad9c0081 Verify @⁠MockitoBean & @⁠MockitoSpyBean can be used with @⁠ContextHierarchy
See gh-33742
2024-10-18 17:10:53 +02:00
Sam Brannen 2aa3f40257 Polishing 2024-10-18 16:55:40 +02:00
Sam Brannen 3842f12d09 Verify that the MockitoExtension and SpringExtension can be combined
See gh-33742
2024-10-18 16:51:52 +02:00
Sam Brannen ac458be845 Polish exception message 2024-10-16 17:49:57 +02:00
Sam Brannen 161d3995bf Introduce BeanOverrideHandler.createOverrideInstance() template method 2024-10-16 17:31:19 +02:00
Sam Brannen da856de100 Revise BeanOverrideRegistrar and rename it to BeanOverrideRegistry 2024-10-16 17:31:19 +02:00
Sam Brannen c0c78bd67e Rename OverrideMetadata for Bean Overrides
Prior to this commit, OverrideMetadata was the only public type in the
org.springframework.test.context.bean.override package whose name did
not start with BeanOverride. In addition, an OverrideMetadata component
plays multiple roles in addition to serving as a holder for metadata.

This commit therefore renames OverrideMetadata to BeanOverrideHandler.

In addition, this commit updates the affected documentation and renames
the following related methods in the Bean Override support.

- BeanOverrideHandler: createOverride() -> createOverrideInstance()
- BeanOverrideHandler: track() -> trackOverrideInstance()
- BeanOverrideProcessor: createMetadata() -> createHandler()
- BeanOverrideContextCustomizer: getMetadata() -> getBeanOverrideHandlers()
- BeanOverrideRegistrar: registerNameForMetadata() -> registerBeanOverrideHandler()
- BeanOverrideRegistrar: markWrapEarly() -> registerWrappingBeanOverrideHandler()

Closes gh-33702
2024-10-16 16:32:38 +02:00
Juergen Hoeller e89218b39a Merge branch '6.1.x' 2024-10-16 13:46:22 +02:00
Juergen Hoeller c765d03a59 Use Locale.ROOT consistently for toLower/toUpperCase
Closes gh-33708
2024-10-16 13:44:59 +02:00
Juergen Hoeller 11d4272ff4 Use Locale.ROOT consistently for toLower/toUpperCase
Closes gh-33708
2024-10-16 13:36:23 +02:00
rstoyanchev bdcfbee7df Merge branch '6.1.x' 2024-10-16 12:11:23 +01:00
rstoyanchev 23656aebc6 Use Locale.ROOT consistently for toLower/toUpperCase
See gh-33708
2024-10-16 12:05:54 +01:00
Simon Baslé dbbc578676 Polishing
Inline `AbstractMockitoTestExecutionListener` since there's now only one
Mockito `TestExecutionListener`.
2024-10-16 10:22:38 +02:00
Simon Baslé 6f79c7e70f Remove support for Mockito annotations and `MockitoSession`
This change remove the support for Mockito annotations, `MockitoSession`
and opening/closing of mocks that was inherited from Boot's `@MockBean`
support, as well as the switch to `MockitoSession` made in 1c893e6.

Attempting to take responsability for things Mockito's own JUnit
Jupiter extension does better is not ideal, and we found it leads to
several corner cases which make `SpringExtension` and `MockitoExtension`
incompatible in the current approach.

Instead, this change refocuses our Mockito bean overriding support
exclusively on aspects specific to the Framework. `MockitoExtension`
will thus be usable in conjunction with `SpringExtension` if one needs
to use `@Captor`/`@InitMocks`/`@Mock`/`@Spy` or other Mockito utilities.

See gh-33318
Closes gh-33692
2024-10-16 09:40:57 +02:00
Sam Brannen 67cb3c77ec Rename BeanOverrideStrategy enum constants
Closes gh-33701
2024-10-15 18:19:59 +02:00
Tran Ngoc Nhan e191c34078 Polishing
Closes gh-33681
2024-10-14 16:44:42 +02:00
Sam Brannen b3cc9a219e Ensure that @⁠MockitoBeanSettings is inherited in @⁠Nested test class
Closes gh-33685
2024-10-11 17:20:53 +02:00
Juergen Hoeller b748cb38c5 Rename to Mockito(Spy)BeanForFactoryBeanIntegrationTests 2024-10-11 16:58:18 +02:00
Sam Brannen eb4bf1c0a6 Support @⁠MockitoBean reset and MockitoSession management with @⁠Nested tests
Prior to this commit, the MockitoResetTestExecutionListener failed to
reset mocks created via @⁠MockitoBean if the @⁠MockitoBean field was
declared in an enclosing class for a @⁠Nested test class. In addition,
the MockitoSession was not properly managed by the
MockitoTestExecutionListener.

This commit addresses those issue as follows.

1) The hasMockitoAnnotations() utility method has been overhauled so
that it finds Mockito annotations not only on the current test class
and on fields of the current test class but also on interfaces,
superclasses, and enclosing classes for @⁠Nested test classes as well
as on fields of superclasses and enclosing classes.

That allows the MockitoResetTestExecutionListener to properly detect
that it needs to reset mocks for fields declared in enclosing classes
for @⁠Nested classes.

2) MockitoTestExecutionListener has been revised so that it only
initializes a MockitoSession before each test method and closes the
MockitoSession after each test method. In addition, it now only manages
the MockitoSession when hasMockitoAnnotations() returns true for the
current test class (which may be a @⁠Nested test class). Furthermore,
it no longer attempts to initialize a MockitoSession during the
prepareTestInstance() callback since that results in an
UnfinishedMockingSessionException for a @⁠Nested test class due to the
fact that a MockitoSession was already created for the current thread
for the enclosing test class.

Closes gh-33676
2024-10-11 16:14:42 +02:00
Sam Brannen 7fb6a2e4f7 Polish Javadoc for Bean Override TestExecutionListeners 2024-10-11 15:50:56 +02:00
Sam Brannen e2d981e809 Extract common logic into AbstractMockitoTestExecutionListener 2024-10-11 10:15:49 +02:00
Simon Baslé 0f25c75b9e Document `TestExecutionListener` implementations introduced in 6.2
Closes gh-33661
2024-10-10 16:32:38 +02:00
Sam Brannen 0e8316e704 Add value attribute alias to @⁠MockitoBean and @⁠MockitoSpyBean
This commit improves the user experience for common use cases by
introducing new `value` attributes in @⁠MockitoBean and
@⁠MockitoSpyBean that are aliases for the existing `name` attributes.

For example, this allows developers to declare
@⁠MockitoBean("userService") instead of @⁠MockitoBean(name =
"userService"), analogous to the existing name/value alias support in
@⁠TestBean.

Closes gh-33680
2024-10-10 13:05:39 +02:00
Sam Brannen 1b8f2c46c1 Update Javadoc for @⁠Mockito[Spy]Bean to reflect current semantics 2024-10-10 12:19:36 +02:00
Sam Brannen f7e32a9c78 Revise singleton destruction for Bean Overrides
See gh-33678
2024-10-10 12:13:44 +02:00
Sam Brannen 8d652e9c12 Reinstate Bean Override support for replacing a manually registered singleton
Closes gh-33678
2024-10-09 18:10:07 +02:00
Sam Brannen c70a6d3be1 Fix test method names 2024-10-09 17:17:57 +02:00
Sam Brannen 1afcb22205 Change enforceOverride flag to false in @⁠TestBean and @⁠MockitoBean
Based on feedback from the Spring Boot team, we have decided to change
the default values for the enforceOverride flags in @⁠TestBean and
@⁠MockitoBean from true to false.

Closes gh-33613
2024-10-09 17:08:58 +02:00
Sam Brannen 381b16fba2 Simplify Bean Override field injection logic
This commit simplifies the field injection logic for Bean Overrides in
order to align with the semantics of the core container and the Spring
TestContext Framework.

Closes gh-33677
2024-10-09 15:43:32 +02:00
Sam Brannen 7c3624318b Polish Mockito TestExecutionListeners 2024-10-09 15:43:32 +02:00
Sam Brannen 461f1724b7 Colocate nonexistent bean definition processing for Bean Overrides 2024-10-09 15:43:32 +02:00
Sam Brannen b5c82b8dcb Reject bean names with factory prefix for Bean Overrides
Closes gh-33674
2024-10-09 15:43:32 +02:00
Sam Brannen c864afd6fe Polishing 2024-10-09 15:43:32 +02:00
Sam Brannen 65d219131c Stop disabling MockitoResetTestExecutionListener within a native image
Instead, MockitoResetTestExecutionListener is now only enabled if the
current test class uses Mockito annotations or Mockito-related
annotations in spring-test.

See gh-32933
2024-10-08 17:41:30 +02:00
Sam Brannen 9a4be95dee Verify registration of runtime hints for Bean Overrides
See gh-32933
2024-10-08 17:41:30 +02:00
Sam Brannen 6a2e234a87 Register runtime hints for BeanOverrideProcessors
This commit introduces a BeanOverrideReflectiveProcessor which
registers runtime hints for any BeanOverrideProcessor configured
via @⁠BeanOverride.

See gh-32933
2024-10-08 17:41:17 +02:00
Sam Brannen 5ddeb06640 Skip pseudo bean definition registration during AOT processing
Prior to this commit, AOT processing failed for tests that made use of
the Bean Override feature to "override" a nonexistent bean. The reason
is that we register a "pseudo" bean definition as a placeholder for a
nonexistent bean, and our AOT support cannot automatically convert that
"pseudo" bean definition to a functional bean definition for use at AOT
runtime.

To address that, this commit skips registration of "pseudo" bean
definitions during AOT processing, and by doing so we enable the JVM
runtime and AOT runtime to operate with the same semantics.

See gh-32933
2024-10-08 17:41:11 +02:00
Sam Brannen ce8e06cf10 Register Bean Override infrastructure beans as manual singletons
Prior to this commit, AOT processing failed for tests that made use of
the Bean Override feature, since the Set<OverrideMetadata> constructor
argument configured in the bean definition for the
BeanOverrideBeanFactoryPostProcessor cannot be properly processed by
our AOT support. The reason is that each OverrideMetadata instance is
effectively an arbitrary object graph that cannot be automatically
converted to a functional bean definition for use at AOT runtime.

To address that, this commit registers Bean Override infrastructure
beans as manual singletons instead of via bean definitions with the
infrastructure role.

See gh-32933
2024-10-08 16:58:59 +02:00
Sam Brannen 98bee41630 Polish BeanOverrideBeanFactoryPostProcessor 2024-10-07 14:22:53 +02:00
Sam Brannen 28b9cf3b83 Simplify and document BeanOverrideTestExecutionListener
This commit simplifies the implementation of
BeanOverrideTestExecutionListener by introducing a static
injectFields() utility method and removing the use of BiConsumers,
records, and duplicated code.

This commit also introduces Javadoc for all methods in
BeanOverrideTestExecutionListener.

Closes gh-33660
2024-10-06 15:05:10 +02:00
Sam Brannen b0c7d15d9f Polishing 2024-10-05 13:57:24 +02:00
Sam Brannen d957d01d14 Polishing 2024-10-04 15:48:26 +02:00
Sam Brannen c4c005b82e Emulate AbstractAotProcessor.process() in AOT endToEndTests() 2024-10-04 15:46:23 +02:00
Sam Brannen fb5e4c0ef2 Remove obsolete method parameter 2024-10-04 11:16:49 +02:00
Sam Brannen 02094b258c Destroy singleton instead of removing and re-registering bean definition 2024-10-03 16:43:59 +02:00
Sam Brannen 39a27256a7 Reduce scope of BeanDefinitionRegistry usage in Bean Override BFPP 2024-10-03 16:39:43 +02:00
Sam Brannen f26a266c41 Optimize BeanOverrideRegistrar lookup in BeanOverrideTestExecutionListener 2024-10-03 16:39:43 +02:00
Sam Brannen d44701f828 Extract WrapEarlyBeanPostProcessor to top-level class 2024-10-03 16:39:43 +02:00
Sam Brannen 4c3bc3ba69 Emulate AbstractAotProcessor.process() in AotIntegrationTests 2024-10-03 16:39:43 +02:00
Sam Brannen 32309e86ce Fix context caching for Bean Overrides w/ different annotation order
Prior to this commit, ApplicationContext caching support was broken if
two Bean Override fields declared the same annotations but in a
different order.

This commit fixes that by switching to Set semantics for the
annotations declared on a Bean Override field.

Closes gh-33633
2024-10-02 11:23:48 +02:00
Sam Brannen a21c557101 Do not replace existing Bean Override definition with pseudo-definition
Prior to this commit, BeanOverrideBeanFactoryPostProcessor replaced
existing bean definitions with "pseudo" bean definitions; however, that
is unnecessary. An existing BeanDefinition is suitable as-is and does
not need to be replaced with a pseudo/fake definition.

To address that, this commit reregisters an existing bean definition
and only registers a new bean definition when creating a bean
definition for a nonexistent bean.

As a side effect, we no longer need to copy primary and fallback flags.

Closes gh-33627
2024-10-01 12:20:27 +02:00
Sam Brannen 1c87e4795d Introduce enforceOverride flag in @⁠TestBean and @⁠MockitoBean
Prior to this commit, @⁠MockitoBean could be used to either create or
replace a bean definition, but @⁠TestBean could only be used to replace
a bean definition.

However, Bean Override implementations should require the presence of
an existing bean definition by default (i.e. literally "override" by
default), while giving the user the option to have a new bean
definition created if desired.

To address that, this commit introduces a new `enforceOverride`
attribute in @⁠TestBean and @⁠MockitoBean that defaults to true but
allows the user to decide if it's OK to create a bean for a nonexistent
bean definition.

Closes gh-33613
2024-09-30 14:32:53 +02:00
Sam Brannen d79258ac73 Reject non-singletons in Test Bean Override support
Prior to this commit, a non-singleton FactoryBean was silently replaced
by a singleton bean. In addition, bean definitions for prototype-scoped
and custom-scoped beans were replaced by singleton bean definitions
that were incapable of creating the desired bean instance. For example,
if the bean type of the original bean definition was a concrete class,
an attempt was made to invoke the default constructor which either
succeeded with undesirable results or failed with an exception if the
bean type did not have a default constructor. If the bean type of the
original bean definition was an interface or a FactoryBean that claimed
to create a bean of a certain interface type, an attempt was made to
instantiate the interface which always failed with a
BeanCreationException.

To address the aforementioned issues, this commit reworks the logic in
BeanOverrideBeanFactoryPostProcessor so that an exception is thrown
whenever an attempt is made to override a non-singleton bean.

Closes gh-33602
2024-09-29 18:12:00 +02:00
Sam Brannen 4e9b503055 Polish OverrideMetadata 2024-09-29 18:02:09 +02:00
Sam Brannen ba1d01d9b7 Add missing final declaration to OverrideMetadata.getBeanName() 2024-09-29 16:31:20 +02:00
Sam Brannen 5c08f81d80 Polishing 2024-09-29 16:28:06 +02:00
Sam Brannen 625614a4d2 Stop "collecting" annotations in MockitoAnnotationDetector
There is no need to collect/track the actual annotations. Rather, we
only need to know if there is at least once such annotation present.
2024-09-29 15:34:40 +02:00
Sam Brannen 40ca83dfd4 Revise Bean Override internals and Javadoc 2024-09-28 17:13:24 +02:00
Sam Brannen bed3025274 Restructure BeanOverrideBeanFactoryPostProcessor and improve documentation 2024-09-27 17:08:08 +02:00
Sam Brannen ea8b8ae910 Polishing 2024-09-27 17:03:49 +02:00
Sam Brannen 9c746905bc Test status quo for Bean Override singleton semantics
The tests introduced in this commit reveal the following issues in our
Bean Override support.

- If a FactoryBean signals it does not manage a singleton, the Bean
  Override support silently replaces it with a singleton.

- An attempt to override a prototype-scoped bean or a bean configured
  with a custom scope results in one of the following.

  - If the bean type of the original bean definition is a concrete
    class, an attempt will be made to invoke the default constructor
    which will either succeed with undesirable results or fail with an
    exception if the bean type does not have a default constructor.

  - If the bean type of the original bean definition is an interface or
    a FactoryBean that claims to create a bean of a certain interface
    type, an attempt will be made to instantiate the interface which
    will always fail with a BeanCreationException.
2024-09-27 15:42:12 +02:00
Sam Brannen c3ff6cf319 Reverse engineer documentation for Bean Override internals 2024-09-27 15:39:35 +02:00
Sam Brannen ded5c13e19 Reinstate BeanOverrideTestSuite 2024-09-27 13:48:56 +02:00
Yanming Zhou 8941e2876e Replace 'e.g.' with 'for example' in documentation and comments
Closes gh-33515
2024-09-26 14:11:17 +02:00
Sam Brannen e55fe9077f Make DynamicPropertyRegistrarBeanInitializer public
In order to allow third parties (for example, Spring Boot) to ensure
that a DynamicPropertyRegistrarBeanInitializer has been registered in
an ApplicationContext which has not been customized by the
DynamicPropertiesContextCustomizer, this commit converts
DynamicPropertyRegistrarBeanInitializer to a public API for use in such
special use cases.

Closes gh-33593
2024-09-26 13:01:57 +02:00
Sam Brannen b943bdeec2 Polishing 2024-09-25 17:28:47 +02:00
Sam Brannen aef5143642 Merge branch '6.1.x' 2024-09-24 16:50:12 +02:00
Sam Brannen 5cc4d0a2ca Do not invoke AotTestExecutionListener for @⁠DisabledInAotMode tests
Closes gh-33589
2024-09-24 16:47:48 +02:00
Sam Brannen 6a9b5d21f4 Document that TestContextAnnotationUtils is required for @⁠Nested support
Closes gh-33586
2024-09-24 11:55:44 +02:00
Sam Brannen 59eaed0b28 Ensure integration tests are suitable for AOT processing 2024-09-23 16:45:56 +02:00
Sam Brannen 7d99790c34 Polishing 2024-09-23 16:45:56 +02:00
Sam Brannen 8931b75b95 Polishing 2024-09-20 10:58:37 +02:00
Johnny Lim 3ba9d35e22 Polish
Closes gh-33566
2024-09-20 10:58:37 +02:00
Sam Brannen e587753b1d Introduce @⁠EasyMockBean bean override example
This commit introduces example support for a custom @⁠EasyMockBean
annotation that allows tests to use EasyMock as the mocking framework
for bean overrides in a test's ApplicationContext.

The point of this exercise is to ensure that it is possible for third
parties to introduce bean override support for mocking frameworks other
than Mockito, and that they can do so with the APIs currently in place.

Closes gh-33562
2024-09-18 17:10:06 +02:00
Sam Brannen 6c2cba5d8a Polish bean override internals 2024-09-18 14:22:15 +02:00
Sam Brannen 13e175ab46 Avoid use of static import in production code 2024-09-16 15:50:05 +02:00
Sam Brannen b60bb44256 Polish test @⁠Configuration classes 2024-09-16 15:45:32 +02:00
Sam Brannen 31a6e98eaf Introduce @⁠Disabled AOT tests for @⁠TestBean support
See gh-32933
2024-09-16 15:43:54 +02:00
Sam Brannen d097eea3a8 Polish DynamicPropertyRegistrar documentation 2024-09-12 13:20:59 +02:00
Sam Brannen e7b52cf8b2 Introduce DynamicPropertyRegistrar to replace DynamicPropertyRegistry bean
Spring Boot's testing support registers a DynamicPropertyRegistry as a
bean in the ApplicationContext, which conflicts with the
DynamicPropertyRegistry registered as a bean by the Spring TestContext
Framework (TCF) since Spring Framework 6.2 M2.

To avoid that conflict and to improve the user experience for Spring's
testing support, this commit introduces a DynamicPropertyRegistrar API
to replace the DynamicPropertyRegistry bean support.

Specifically, the TCF no longer registers a DynamicPropertyRegistry as
a bean in the ApplicationContext.

Instead, users can now register custom implementations of
DynamicPropertyRegistrar as beans in the ApplicationContext, and the
DynamicPropertiesContextCustomizer now registers a
DynamicPropertyRegistrarBeanInitializer which eagerly initializes
DynamicPropertyRegistrar beans and invokes their accept() methods with
an appropriate DynamicPropertyRegistry.

In addition, a singleton DynamicValuesPropertySource is created and
registered with the Environment for use in
DynamicPropertiesContextCustomizer and
DynamicPropertyRegistrarBeanInitializer, which allows
@⁠DynamicPropertySource methods and DynamicPropertyRegistrar beans to
transparently populate the same DynamicValuesPropertySource.

Closes gh-33501
2024-09-11 17:42:04 +02:00
Stéphane Nicoll e311d9848a Expose the uriTemplate used to build a MockHttpServletRequest
This commit exposes the unexpanded URI template used to build a
MockHttpServletRequest. This allows MockMvc users to retrieve that
information, in consistency with ExchangeResult in WebTestClient.

Closes gh-33509
2024-09-09 14:46:05 +02:00
Brian Clozel 52c4ffa4d2 Merge branch '6.1.x' 2024-08-30 21:23:29 +02:00
Brian Clozel fab889009a Support multiple async starts in MockHttpServletRequest
Closes gh-33457
2024-08-30 20:08:36 +02:00
rstoyanchev 7aa25e083a Merge branch '6.1.x' 2024-08-28 18:59:47 +03:00
rstoyanchev 186deb777f Update deprecation notices on rawStatusCode
Mark for removal where not marked, and set to 7.0
consistently as the target for removal.

See gh-33440
2024-08-28 18:49:49 +03:00
rstoyanchev 57cb8c7abf Restore rawStatusCode methods
Revert methods removed in 7df2e2a8d2.

See gh-33440
2024-08-28 18:12:26 +03:00
Sam Brannen 5bcfcdd0be Polishing 2024-08-28 14:46:12 +02:00
Sam Brannen 38a56b3fda Unwrap CGLIB proxy when invoking non-proxied methods in ReflectionTestUtils
Prior to this commit, when ReflectionTestUtils was used to invoke a
method on a CGLIB proxy, the invocation was always performed directly
on the proxy. Consequently, if the method was not proxied/intercepted
by the CGLIB proxy -- for example, if the method was final or
effectively private -- the invoked method could not operate on the
state of the target object or interact with other private methods in
the target object.

With this commit, if the supplied target object is a CGLIB proxy which
does not intercept the method, the proxy will be unwrapped allowing the
method to be invoked directly on the ultimate target of the proxy.

Closes gh-33429
2024-08-28 14:31:24 +02:00
Sam Brannen 4a099d213e Add missing @⁠TestMethodOrder declarations 2024-08-19 14:46:21 +02:00
Simon Baslé 107ae6159b Add tests for MockitoBean reset of mocks/spies from a FactoryBean
Closes gh-33405
2024-08-19 11:10:19 +02:00
Sébastien Deleuze 94d8fc7af8 Merge branch '6.1.x' 2024-08-19 10:46:54 +02:00
Sébastien Deleuze 0101945708 Prevent a leak in WebTestClient
This commit applies the same kind of processing for
Void.class element type in the ParameterizedTypeReference
variant of WebTestClient.ResponseSpec#returnResult than
in the Class variant.

Closes gh-33389
2024-08-19 10:46:47 +02:00
Sam Brannen 59c779d8fe Enforce order of Javadoc tags for records introduced in 6.2
See gh-33403
2024-08-18 13:12:47 +02:00
Sam Brannen d749d2949d Use new features from JUnit Jupiter 5.11
This commit primarily migrates to the new argumentSet() feature but also
applies additional polishing to our use of parameterized tests.

See gh-33395
2024-08-16 13:48:19 +02:00
Sam Brannen f6110dda06 Polishing 2024-08-08 17:48:57 +03:00
Simon Baslé 70e5af7d16 Polishing: remove unnecessary code 2024-08-07 16:57:52 +02:00
Simon Baslé 52bc3cf5aa Polishing 2024-08-07 16:43:09 +02:00
Stéphane Nicoll 313b063aef Polish 2024-08-07 15:28:52 +02:00
Simon Baslé 7052af97a6 Polish test to focus on the FactoryBean results being mocked 2024-08-07 14:57:15 +02:00
Simon Baslé 1c893e6354 Add `@MockitoBeanSettings`, use MockitoSession with strict stubs default
This commit changes the way the `MockitoTestExecutionListener` sets up
mockito, now using the `MockitoSession` feature. Additionally, stubbing
now defaults to a STRICT mode which can be overruled with a newly
introduced annotation: `@MockitoBeanSettings`.

Closes gh-33318
2024-08-07 14:57:15 +02:00
Sanghyuk Jung ca377e4854 Remove duplicated "the" in Javadoc
See gh-33308
2024-08-03 09:52:23 +02:00
rstoyanchev 31a3119784 Add FilterRegistration's defensively
Follow-up to d2225c, which broke Boot tests because the ServletContext can
be the one of the embedded Servlet container if initializing a live server
and as well as MockMvc (e.g. via `@AutoConfigureMockMvc`).

See gh-33252
2024-07-31 14:50:08 +03:00
rstoyanchev 5ac7e74bf2 Replace test FilterRegistration with the one in testFixtures
See gh-33252
2024-07-30 11:33:47 +03:00
rstoyanchev d2225c2140 MockMvc supports FilterRegistration filter init
Closes gh-33252
2024-07-30 11:33:47 +03:00
Stéphane Nicoll 70f3b0eb91 Only register DynamicPropertySourceBeanInitializer if necessary
This commit makes sure to check first if
DynamicPropertySourceBeanInitializer has been registered before trying
to register it.

When running with AOT optimizations, the bean definition has been
contributed so there is no need to register it again when the context
customizer runs.

Closes gh-33272
2024-07-29 09:30:27 +02:00
Stéphane Nicoll 89453905cb Copy tests for multipart request builder
See gh-33229
2024-07-18 12:11:59 +02:00
Stéphane Nicoll 6590ab6bf9 Consistently set content type of the request with multipart
Closes gh-33232
2024-07-18 12:01:47 +02:00
Stéphane Nicoll 265299c790 Restore source and binary compatibility in MockMvc
Previous to this commit, MockHttpServletRequestBuilder was not binary
compatible as its methods had moved to a parent class with a generic
argument on the return type. MockMultipartHttpServletRequestBuilder
was also not source compatible as it no longed extended from
MockHttpServletRequestBuilder.

Both these changes were introduced to allow the AssertJ support to
expose builders that implement an extra AssertJ interface, without
copying the features the builders provide.

This commit restore compatibility. For MockHttpServletRequestBuilder
we simply override all methods that returns the generic type into
the resolved type.

MockMultipartHttpServletRequestBuilder is more involved. Because we
need to extend from MockHttpServletRequestBuilder, we have no other
choice than duplicating the code. For now, the abstract builder for
multipart is only used by the AssertJ support, but we can revisit this
again in a major release.

Closes gh-33229
2024-07-18 11:21:35 +02:00
Sam Brannen 3e48498663 Change MIME mapping for .js from application/javascript to text/javascript
This application/javascript MIME type is deprecated.

This commit therefore changes the MIME type mapping for *.js files from
application/javascript to text/javascript in order to align with
industry standards.

Closes gh-33197
2024-07-12 18:22:18 +02:00
rstoyanchev 545228d693 Remove unused tiles config files 2024-07-08 12:47:10 +01:00
Stéphane Nicoll f1658079a5 Polish documentation for RegisterReflection
See gh-29194
2024-07-06 09:31:12 +02:00
Stéphane Nicoll db1e6e1e26 Polish 2024-07-05 08:26:27 +02:00
Stéphane Nicoll ca8bd7b06b Simplify tests 2024-07-04 16:34:33 +02:00
Stéphane Nicoll 4bdb772d39 Introduce HttpMessageContentConverter
This commit introduces an abstraction that allows to convert HTTP
inputs to a data type based on a set of HttpMessageConverter.

Previously, the AssertJ integration was finding the first converter
that is able to convert JSON to a Map (and vice-versa) and used that
in its API. With the introduction of SmartHttpMessageConverter, exposing
a specific converter is fragile.

The added abstraction allows for converting other kind of input than
JSON if we need to do that in the future.

Closes gh-33148
2024-07-04 14:06:00 +02:00
Sam Brannen abcad5dbcf Support property placeholders in @⁠Sql script paths
Prior to this commit, paths configured via the scripts attribute in
@⁠Sql were required to be final paths without dynamic placeholders;
however, being able to make script paths dependent on the current
environment can be useful in certain testing scenarios.

This commit introduces support for property placeholders (${...}) in
@⁠Sql script paths which will be replaced by properties available in
the Environment of the test's ApplicationContext.

Closes gh-33114
2024-07-03 17:16:53 +02:00
Sam Brannen 932ce04541 Stop referring to old Spring versions in Javadoc 2024-07-01 17:50:52 +02:00
Sam Brannen cc002875c4 Support fully-qualified factory method names in @⁠TestBean
Prior to this commit, @⁠TestBean factory methods had to be defined in
the test class, one of its superclasses, or in an implemented
interface. However, users may wish to define common factory methods in
external classes that can be shared easily across multiple test classes
simply by referencing an external method via a fully-qualified method
name.

To address that, this commit introduces support for referencing a
@⁠TestBean factory method via its fully-qualified method name following
the syntax <fully-qualified class name>#<method name>.

Closes gh-33125
2024-06-30 21:16:04 +02:00
Sam Brannen c2f8d4803f Update Javadoc for @⁠TestBean 2024-06-30 21:15:56 +02:00
Sam Brannen b105fdc87a Polishing 2024-06-30 14:41:43 +02:00
Sébastien Deleuze 1d363e5a41 Use UTF-8 with JSON in MockHttpServletResponse
This commit makes MockHttpServletResponse consistent with the other
parts of the framework where the body of a response is read as an UTF-8
String when the content type is application/json or similar, overriding
the ISO-8859-1 default Servlet encoding.

Closes gh-33019
2024-06-19 09:33:43 +02:00
Stéphane Nicoll 1eaa9cd2f4 Polish 2024-06-18 16:04:19 +02:00
Stéphane Nicoll 24bbc6d80d Improve support of async request in MockMvcTester
This commit improves the handling of asynchronous requests by offering
a way to opt-in for the raw async result. This provides first class
support for asserting a request that might still be in process as well
as the asyncResult, if necessary.

See gh-33040
2024-06-18 15:19:47 +02:00
Stéphane Nicoll a7503e7200 Add explicit support for asynchronous requests in MockMvcTester
This commit makes asynchronous requests first class by providing a
MvcTestResult that represents the final, completed, state of a request
by default. Previously, the result was an intermediate step that may
require an ASYNC dispatch to be fully usable. Now it is de facto
immutable.

To make things a bit more explicit, an `.exchange(Duration)` method has
been added to provide a dedicated time to wait. The default applies a
default timeout that is consistent with what MVcResult#getAsyncResult
does.

Given that we apply the ASYNC dispatch automatically, the intermediate
response is no longer available by default. As a result, the asyncResult
is not available for assertions.

As always, it is possible to use plain MockMvc by using the `perform`
method that takes the regular RequestBuilder as an input. When this
method is invoked, no asynchronous handling is done.

Closes gh-33040
2024-06-18 13:03:09 +02:00
Stéphane Nicoll a1b0099795 Add missing debug(Writer) alternative
See gh-33059
2024-06-18 12:40:29 +02:00
Stéphane Nicoll acf73404c1 Simplify Mock[Multipart]HttpServletRequestBuilder
This commit simplifies the package private constructors on those two
builders now that the URI can be specified by dedicated builder methods.

Closes gh-33062
2024-06-18 10:10:07 +02:00
Stéphane Nicoll d76f37c90b Add multipart support for MockMvcTester
File uploads with MockMvc require a separate
MockHttpServletRequestBuilder implementation. This commit applies the
same change to support AssertJ on this builder, but for the multipart
version.

Any request builder can now use `multipart()` to "down cast" to a
dedicated multipart request builder that contains the settings
configured thus far.

Closes gh-33027
2024-06-18 09:43:08 +02:00
Stéphane Nicoll f2137c99e5 Add debug support for MvcResult
This commit adds a debug() shortcut to print the detail of a MvcResult
to ease debugging when a request did not work as expected.

Closes gh-33059
2024-06-18 06:43:26 +02:00
Stéphane Nicoll 84bcb65dd1 Streamline assertions on exceptions
This commit simplifies assertions on MockMvc requests that have failed
to process. A now general hasFailed/doesNotHaveFailed/failure provides
the necessary to assert the exception.

Any attempt to access anything from the result with an unresolved
exception still fails as before.

Closes gh-33060
2024-06-18 06:23:13 +02:00
Stéphane Nicoll 1582f5f7d1 Handle URI as candidate for a merge from a parent builder
Closes gh-33057
2024-06-17 17:06:10 +02:00
Stéphane Nicoll b8790077b9 Polish 2024-06-17 16:47:37 +02:00
Stéphane Nicoll 69c44dee99 Add support for conversion of the whole JSON document
Closes gh-33018
2024-06-13 00:12:33 +02:00
Stéphane Nicoll 1d0af7e5d3 Move TestBeanFactory to example package 2024-06-12 11:05:22 +02:00
Stéphane Nicoll 3f2d9c372d Migrate "Failing" test cases to regular tests
This commit replaces the use of EngineTestKit to test scenarios where
bean override could not process the test class. There is no need to
run an actual test for this as:

1. Regular integration tests are already validating that adding the
annotation triggers the processing as part of executing the test.
2. The entry point is a ContextCustomizer that can easily be invoked
in a regular test.

As part of harmonizing this, AbstractTestBeanIntegrationTestCase can
be nested, and BeanOverrideTestSuite serve no purpose. The tests can
be executed in an IDE without any special setup.
2024-06-12 11:03:14 +02:00
Stéphane Nicoll 1318f65223 Harmonize test class names
This commit harmonizes the class names of the bean override support by
using a consistent prefix for integration test, inspire from the one
that was used in Spring Boot
2024-06-12 08:54:24 +02:00
Stéphane Nicoll 2d48371c6d Revert polish on Bean Override support
This commit revers the removal of the `private` keyword in the examples
of the reference documentation and the tests for consistency. While the
default visibility makes the example more concise, it could imply to the
reader that the field (or the factory method) cannot be private.

Also, there is no need to multiply anything returned from `Objects.hash`
as its very distinct on its own already.
2024-06-12 08:11:18 +02:00
Sam Brannen 46dccd8f97 Polishing 2024-06-11 16:39:24 +02:00
Sam Brannen f481a4b60b Polish reference documentation 2024-06-11 16:31:56 +02:00
Arjen Poutsma 60b5bbe334 Introduce request attributes in RestClient
This commit introduces request attributes in the RestClient and
underlying infrastructure (i.e. HttpRequest).

Closes gh-32027
2024-06-11 15:51:29 +02:00
Stéphane Nicoll 2a680934ee Harmonize equals/hashCode of OverrideMetadata to use class identity
This commit harmonizes the equals/hashCode behavior of OverrideMetadata
to always take the implementation class as a factor for its identity.

This is important as two OverrideMetadata implementations could use
the same strategy and other settings while creating the override value
in a totally different way. This commit makes sure they are identified
as different.

Closes gh-33005
2024-06-11 12:03:31 +02:00
Stéphane Nicoll 1be92f82af Polish 2024-06-11 11:58:19 +02:00
Stéphane Nicoll 28f62abda4 Use the field name as a fallback qualifier for Bean Overriding
This commit harmonizes how a candidate bean definition is determined
for overriding using `@TestBean`, `@MockitoBean`, and `@MockitoSpyBean`.

Previously, a qualifier was necessary even if the name of the annotated
field matches the name of a candidate. After this commit, such candidate
will be picked up transparently, the same it is done for regular
autowiring.

This commit also reviews the documentation of the feature as considering
the field means that its name is taken into account to compute a cache
key if by-type lookup is requested.

Closes gh-32939
2024-06-11 11:30:01 +02:00
Stéphane Nicoll b9a6ba1242 Fix package tangle in bean override tests
This commit fixes a package tangle between the root bean override
package and its sub-packages. This was vastly improved with the
introduction of `@DummyBean` but we still had a few tests that were
at the wrong place.
2024-06-10 15:23:36 +02:00
Stéphane Nicoll 96302a7102 Stop using a conventional suffix for TestBean factory methods
This commit changes how factory method for `@TestBean` usage is
discovered. Previously the field name or bean name suffixed with
'TestOverride' was used. It sounds more natural to just use the
field name or bean name, leaving cases where a suffix is required
to explicitly providing the method name.

As part of this change, the exception messages have been revisited as
it's less since the method name candidates have the exact same name
as the field or bean name. A `()` is added to make it more clear the
name is for a method.

Closes gh-32940
2024-06-10 12:52:21 +02:00
Stéphane Nicoll 45e9f04b57 Remove TestOverrideMetadata and use dummy implementation
TestOverrideMetadata was doing byName lookup by default, even without
a bean name. This makes writing tests that need to do by type lookup
way more complicated that it should.

This commit introduces DummyBean, that merely replaces two types with
hardcoded values. It also exposes the raw attribute of OverrideMetadata
and doesn't override anything from it to make sure the behavior is not
altered.

Closes gh-32982
2024-06-10 11:27:27 +02:00
Stéphane Nicoll 536de9ac80 Allow MockitoBean to create a mock for a bean that does not exist
This commit aligns the by-type lookup for bean overrides with what was
done when a bean name is present. It now correctly generate a bean
name rather than failing because no bean of that type exists.

Closes gh-32990
2024-06-10 09:57:27 +02:00
Stéphane Nicoll 7916f74942 Review TCF cache support for bean override
This commit reviews how bean override support can influence the key of
an application context cached by the TCF. OverrideMetadata and its
subclasses now implement a proper equals/hashCode pair that is tested
in various scenarios.

Due to how the TCF operates, OverrideMetadata has to be computed in
two locations:

1. In a ContextCustomizerFactory, using the metadata in the enclosing
class if any. This determines whether a customizer is needed in the
first place. The computed set of unique metadata identifies the
customizer and participates in the application context cache's key.
2. In the TestExecutionListener so that it knows the override points
it has to process.

Parsing of the metadata based on a test class has been greatly
simplified and moved to OverrideMetadata proper as we don't need several
flavors. 1 and 2 are using the same algorithm with the former wrapping
that in a Set to compute a proper key.

BeanOverrideContextCustomizerEqualityTests provides a framework for
testing edge cases as we only care about whether the created
ContextCustomizer behaves correctly against the identity of another.

Closes gh-32884
2024-06-07 16:44:57 +02:00
Stéphane Nicoll 02517e5011 Polish
This commit reviews the structure of several classes to comply with
our guidelines. Also, rather than exposing a static method to configure
the context in a test, we call the high-level API directly.
2024-06-07 16:44:57 +02:00
Stéphane Nicoll 0165529d97 Align OverrideMetadata arguments and harmonize bean name
Rather than having to override the getBeanName method when there is one,
this commit moves it as a @Nullable argument. This makes sure that
equals and hashCode consistently use the bean name. getBeanName cannot
be final just yet as the test infrastructure overrides it.

Also, arguments are now ordered consistently, which improves code
readability and type signature.
2024-06-07 16:44:57 +02:00
Stéphane Nicoll 8b66eca932 Harmonize OverrideMetadata implementations
This commit makes sure that each OverrideMetadata implementation is
a top level class with a consistent name.
2024-06-07 16:44:57 +02:00
Brian Clozel e8c122c00a Fix MockCookie Partitioned support
See gh-31454
2024-06-07 14:49:15 +02:00
Brian Clozel 7fc4937199 Add Partitioned cookie attribute support for servers
This commit adds support for the "Partitioned" cookie attribute in
WebFlux servers and the related testing infrastructure.
Note, Undertow does not support this feature at the moment.

Closes gh-31454
2024-06-07 10:03:52 +02:00
Simon Baslé 0758ae5ead Polishing: remove unused import 2024-06-06 16:55:12 +02:00
Simon Baslé d38e4d869f Better support for FactoryBeans in BeanOverrideBeanFactoryPostProcessor
This commit makes sure to account for FactoryBean names when registering
a bean override. In the case of ReplaceDefinition mode, if there is a
factory bean name, it is used to check singleton status and as the name
in the registrar.

Closes gh-32971
2024-06-06 15:49:40 +02:00
Alexej Timonin 416eff1b04 Fix typo in WebTestClient expectedXml
Closes gh-32969
2024-06-06 14:24:40 +02:00
Arjen Poutsma 859b97ce05 Revert "Do not read Map in FormHttpMessageConverter"
This reverts commit 726ac9110c and
80faa94afc.

See gh-32826
2024-06-06 12:39:18 +02:00
Sam Brannen 667b74b53f Return all events from EngineTestKitUtils.executeTestsForClass() 2024-06-05 16:29:11 +02:00
Sam Brannen 9e1ef83669 Avoid issues with system line separator in tests
See f10caf6aa6
2024-06-05 12:36:58 +02:00
Juergen Hoeller 28eb9aebcf Add BeanFactoryInitializer callback before preInstantiateSingletons
Closes gh-32836
2024-06-04 22:50:42 +02:00
Juergen Hoeller f10caf6aa6 Compare text with system line separator (for Windows compatibility)
See gh-32756
2024-06-04 22:50:14 +02:00
Sam Brannen cf3171dae0 Find unique @⁠TestBean factory methods in class hierarchy
I accidentally introduced a regression in commit d185bb1d97 by no
longer checking the number of unique method names found when searching
for @⁠TestBean factory methods.

This commit reintroduces that check and introduces a proper unit test
in TestBeanOverrideProcessorTests.

It turns out that we already had an integration test that was intended
to check for this scenario; however, that test actually did not test
this scenario due to a copy-and-paste error. Thus, this commit also
updates TestBeanInheritanceIntegrationTests so that
fieldInSupertypeWithPrioritizedFactoryMethodInSubtype() tests what it's
supposed to.
2024-06-04 18:47:32 +02:00
Sam Brannen 069c6788f5 Polishing 2024-06-04 18:47:32 +02:00
Stéphane Nicoll aa4b226a22 Add support for converting json values using AssertFactory
This commit benefits from a feature introduced in AssertJ 3.26.0, see
https://github.com/assertj/assertj/pull/3377.

This allows to use any AssertFactory and convert the actual value to
the type the factory manages. Previously, we were using
ParameterizedTypeReference to express the type with its generic
signature but the returned assert object would not be narrowed to the
converted type.

Thanks to this change, we can request to convert the actual value to
`InstanceOfAssertFactories.list(Member.class)` and get a `ListAssert`
of `Member` as a result, rather than an `ObjectAssert` of `List<User>`.

Thanks very much to @scordio for his efforts.

Closes gh-32953
2024-06-04 17:11:08 +02:00
Sam Brannen 4d961fa472 Find @⁠TestBean factory methods in multi-level @⁠Nested hierarchy
Prior to this commit, a @⁠TestBean factory method was found in the
directly enclosing class for a @⁠Nested test class; however, such a
factory method was not found in the enclosing class of the enclosing
class, etc.

This commit updates the search algorithm for @⁠TestBean factory methods
so that it recursively searches the enclosing class hierarchy for
@⁠Nested test classes.

Closes gh-32951
2024-06-04 15:36:40 +02:00
Sam Brannen f68130d2e5 Update Javadoc for @⁠TestBean support
See gh-32943
2024-06-04 15:12:06 +02:00
Sam Brannen acdd8a0015 Improve exception handling in bean override support
- Do not silently abort bean override processing if the ApplicationContext
  is not a BeanDefinitionRegistry.

- Include conflicting bean names in error messages instead of just the
  number of conflicting beans.

- Consistently throw IllegalStateException.

- etc.
2024-06-03 16:57:19 +02:00
Sam Brannen d185bb1d97 Support @⁠TestBean factory methods defined in interfaces
Prior to this commit, @⁠TestBean factory methods were required to be
defined in the test class or one of its superclasses. However, users
may wish to define common factory methods in interfaces that can be
shared easily across multiple test classes simply by implementing the
necessary interface(s).

This commit therefore switches from ReflectionUtils to
MethodIntrospector to find @⁠TestBean factory methods in implemented
interfaces within the type hierarchy of the test class.

Closes gh-32943
2024-06-03 16:04:46 +02:00
Sam Brannen 9ceaf21d24 Extract findMethods() logic in TestBeanOverrideProcessor 2024-06-03 14:56:43 +02:00
Sam Brannen 1536f34fff Fix broken tests 2024-06-03 14:40:13 +02:00
Sam Brannen 8047a22237 Polish TestBeanOverrideProcessor 2024-06-03 13:29:50 +02:00
Sam Brannen 742c41a568 Polishing 2024-05-31 16:18:31 +02:00
Sam Brannen 3a448701f7 Improve class names 2024-05-31 15:49:26 +02:00
Sam Brannen 87c93d35d6 Revise bean override tests with a focus on AOT support
As a follow up to the previous commit (31f8e12adb), this commit
polishes bean override tests and revises them with a focus on AOT
testing support and simplified maintenance.

- Introduce EngineTestKitUtils to simplify working with JUnit's
  EngineTestKit.

- Use idiomatic EngineTestKit APIs to simplify assertions on
  EngineTestKit results.

- Introduce BeanOverrideTestSuite to simplify running all bean override
  tests within the IDE.

- Separate failure and success scenario tests, so that failure tests do
  not launch the JUnit Platform to run tests using the Spring
  TestContext Framework (TCF) within a test class that itself uses the
  TCF.

- Make AbstractTestBeanIntegrationTestCase actually abstract.

- Rename test case classes to give them meaningful names and simplify
  understanding of what's being tested.

- Ensure tests for @⁠MockitoSpyBean functionality use @⁠MockitoSpyBean
  instead of @⁠MockitoBean.

- Declare @⁠Configuration classes local to @⁠SpringJUnitConfig test
  classes whenever possible.

See gh-29122
See gh-32925
2024-05-31 12:19:31 +02:00
Sam Brannen 31f8e12adb Separate failure and success scenario tests for @⁠TestBean
This commit also ensures that @⁠Bean methods are declared within
@⁠Configuration classes instead of within test classes.

See gh-29122
2024-05-29 14:21:58 +02:00
Sam Brannen 1f537b97d5 Demonstrate how to disable Bean Override tests in AOT mode
See gh-29122
2024-05-29 14:20:35 +02:00
Sam Brannen cade3c7b0e Ensure MockMvcTesterIntegrationTests runs in AOT mode
See gh-29122
2024-05-29 13:32:22 +02:00
Sam Brannen a0c9a204b8 Polishing 2024-05-29 13:32:02 +02:00
Stéphane Nicoll 8d2bc3bdba Add support for fluent preparation of the request in MockMvcTester
See gh-32913
2024-05-28 15:29:14 +02:00
Stéphane Nicoll a3e7fd47c6 Allow MockHttpServletRequestBuilder to support AssertJ
This commit moves the features of MockHttpServletRequestBuilder in
an abstract class so that another class can offer the same feature
whilst providing AssertJ support. This wasn't possible previously as
the builder's return type would lose the concrete builder types.

This change benefits MockMultipartHttpServletRequestBuilder that can
use the same mechanism to offer additional settings.

This change also makes it so that a builder instance can be created
using only the HttpMethod. Previously, the URI had to be provided as
well and that makes it impossible to specify it using the builder.

See gh-32913
2024-05-28 15:29:14 +02:00
Stéphane Nicoll fc54cf4430 Harmonize use of uri in MockMvc
Closes gh-32915
2024-05-28 11:17:40 +02:00
Stéphane Nicoll 2d1e58b928 Polish 2024-05-28 09:31:44 +02:00
Stéphane Nicoll f6504c5f91 Deprecate use of raw String for HttpMethod in MockMvc
Closes gh-32914
2024-05-28 09:24:08 +02:00
Stéphane Nicoll e2c5887cea Allow JSON content assertions to be nested
Previously, AbstractJsonContentAssert worked on a raw String, which
made standard AssertJ nested calls, such as satisfies, to return an
assert on the raw string, rather than one with JSON support.

This commit rework AbstractJsonContentAssert so that it no longer
extend from AbstractStringAssert. This makes the list of methods more
focused on JSON assertions, and allow standard operations to provide
the right assert object.

Closes gh-32894
2024-05-27 09:25:12 +02:00
Arjen Poutsma 903493e9a9 Various MultiValueMap improvements
This commit makes several improvements to MultiValueMap:
- asSingleValueMap offers a single-value view (as opposed to the
  existing toSingleValueMap, which offers a copy)
- fromSingleValue is a static method that adapts a Map<?,?> to the
  MultiValueMap interface
- fromMultiValue is a static method that adapts a Map<?,List<?>> to the
  MultiValueMap interface

Closes gh-32832
2024-05-24 11:44:55 +02:00
Stéphane Nicoll 97647ef5f6 Flag tests using deprecated json method deprecated
See gh-32791
2024-05-24 11:03:33 +02:00
Stéphane Nicoll 0ac7e41beb Provide an implementation of JsonComparator
See gh-32791
2024-05-23 16:17:02 +02:00