Commit Graph

3036 Commits

Author SHA1 Message Date
rstoyanchev 2ed281f6a8 Remove deprecated WebFlux APIs
See gh-33809
2025-01-16 15:47:52 +00:00
rstoyanchev 83c020eea5 Remove deprecated HttpStatus codes
See gh-33809
2025-01-15 16:26:16 +00:00
rstoyanchev 9f77d5ff1f Remove deprecated ThemeResolver support
See gh-33809
2025-01-15 16:26:16 +00:00
Sam Brannen 6a81de95ab Merge branch '6.2.x' 2025-01-15 17:16:51 +01:00
Sam Brannen 9181cce65f Support @⁠MockitoBean at the type level on test classes
Prior to this commit, @⁠MockitoBean could only be declared on fields
within test classes, which prevented developers from being able to
easily reuse mock configuration across a test suite.

With this commit, @⁠MockitoBean is now supported at the type level on
test classes, their superclasses, and interfaces implemented by those
classes. @⁠MockitoBean is also supported on enclosing classes for
@⁠Nested test classes, their superclasses, and interfaces implemented
by those classes, while honoring @⁠NestedTestConfiguration semantics.

In addition, @⁠MockitoBean:

- has a new `types` attribute that can be used to declare the type or
  types to mock when @⁠MockitoBean is declared at the type level

- can be declared as a repeatable annotation at the type level

- can be declared as a meta-annotation on a custom composed annotation
  which can be reused across a test suite (see the @⁠SharedMocks
  example in the reference manual)

To support these new features, this commit also includes the following
changes.

- The `field` property in BeanOverrideHandler is now @⁠Nullable.

- BeanOverrideProcessor has a new `default` createHandlers() method
  which is invoked when a @⁠BeanOverride annotation is found at the
  type level.

- MockitoBeanOverrideProcessor implements the new createHandlers()
  method.

- The internal findHandlers() method in BeanOverrideHandler has been
  completely overhauled.

- The @⁠MockitoBean and @⁠MockitoSpyBean section of the reference
  manual has been completely overhauled.

Closes gh-33925
2025-01-15 17:13:35 +01:00
Sam Brannen 8b6523a35b Cross reference @⁠NestedTestConfiguration for Bean Overrides 2025-01-15 17:13:35 +01:00
Simon Baslé caf84ffe7d Revisit HttpHeadersAssert after HttpHeaders API changes
- add various assertions to HttpHeadersAssert
 - improve assertion test coverage
 - remove niche size assertions

Closes gh-34168

Co-authored-by: Stephane Nicoll <stephane.nicoll@broadcom.com>
2025-01-15 11:42:59 +01:00
Stéphane Nicoll 448d6c6ebf Merge branch '6.2.x' 2025-01-15 11:22:23 +01:00
Stéphane Nicoll d280358e98 Fix typo in HttpHeadersAssert#doesNotContainHeaders
This commit deprecates the existing doesNotContainsHeaders in favor of a
newly introduced method that does not have the typo.

Closes gh-34263
2025-01-15 11:19:00 +01:00
Sébastien Deleuze e2216ddc32 Specify generic type nullness in spring-test
See gh-34140
2025-01-14 12:35:02 +01:00
Sam Brannen b9c1aec62f Merge branch '6.2.x' 2025-01-14 11:38:45 +01:00
Sam Brannen 3c3b8c7aac Track only qualifier annotations in BeanOverrideHandler
Closes gh-34260
2025-01-14 11:35:00 +01:00
Sam Brannen 5a68d1f029 Remove @⁠FunctionalInterface declaration from BeanOverrideProcessor
Closes gh-34259
2025-01-14 11:29:45 +01:00
Sam Brannen ff9b7678a7 Polish Bean Override internals and tests 2025-01-14 11:25:37 +01:00
Brian Clozel d28c0396c9 Update runtime hints predicates after GraalVM changes
As of gh-33847, method and field introspection is included by default
when a type is registered for reflection.
Many methods in ReflectionHintsPredicates are now mostly useless as their
default behavior checks for introspection.

This commit deprecates those methods and promotes instead invocation
variants. During the upgrade, developers should replace it for an
`onType` check if only reflection is required. If they were checking for
invocation, they should use the new 'onXInvocation` method.

Closes gh-34239
2025-01-13 15:34:34 +01:00
Stéphane Nicoll 4d0f1729cb Restore deprecated constructor for binary compatibility support
Code that compiles against the non-deprecated version does not see the
new constructor that has been introduced. As such, there is no way for
them to migrate to it without resorting to reflection.

This commit restores the deprecated constructor so that people can try
the latest version more easily.

Closes gh-34238
2025-01-10 18:07:53 +01:00
rstoyanchev 2561a60968 Update MockRestServiceServer bufferContent
Connect the existing bufferContent option to the new RestClient and
RestTemplate equivalent feature.

See gh-33785
2025-01-10 14:39:24 +00:00
Sébastien Deleuze ec48c47886 Make URI template variables nullable
Closes gh-34221
2025-01-10 11:39:21 +01:00
Sébastien Deleuze 483985b173 Suppress serialization warnings
This commit suppresses serialization warnings triggered by the upgrade
of javac from 17 to 23.

See gh-34220
2025-01-09 16:01:30 +01:00
Sam Brannen e8788c7e3e Merge branch '6.2.x' 2025-01-07 17:32:42 +02:00
Sam Brannen cd2fbb1ec5 Properly resolve @⁠TestBean factory method within class hierarchy
Prior to this commit, the search algorithm used to locate a @⁠TestBean
factory method within a test class hierarchy incorrectly found factory
methods declared in subclasses or nested test classes "below" the class
in which the @⁠TestBean field was declared. This resulted in "duplicate
bean override" failures for @⁠TestBean overrides which are clearly not
duplicates but rather "overrides of an override".

This commit ensures that @⁠TestBean factory method resolution is
consistent in type hierarchies as well as in enclosing class
hierarchies (for @⁠Nested test classes) by beginning the search for a
factory method in the class which declares the @⁠TestBean field.

Closes gh-34204
2025-01-07 17:20:52 +02:00
Sam Brannen a3594e7207 Merge branch '6.2.x' 2025-01-07 11:53:04 +02:00
Sam Brannen e8745522fc Polishing 2025-01-07 11:52:33 +02:00
Sam Brannen bc499df6ce Merge branch '6.2.x' 2025-01-05 17:01:12 +02:00
Sam Brannen 181db1db75 Update copyright headers to 2025 2025-01-05 17:00:47 +02:00
Sam Brannen 7b1cdb5efb Merge branch '6.2.x' 2025-01-05 12:18:52 +02:00
Sam Brannen ef4f1f0a71 Ensure @⁠BeanOverride in subclass takes precedence over superclass
Prior to this commit, a @⁠BeanOverride (such as @⁠TestBean) for a
specific target bean which was declared in a superclass always took
precedence over a bean override for the same target bean in a subclass,
thereby rendering the bean override configuration in the subclass
useless. In other words, there was no way for a test class to override
a bean override declared in a superclass.

To address that, this commit switches from direct use of
ReflectionUtils.doWithFields() to a custom search algorithm that
traverses the class hierarchy using tail recursion for processing
@⁠BeanOverride fields (delegating now to
ReflectionUtils.doWithLocalFields() in order to continue to benefit
from the caching of declared fields in ReflectionUtils).

Closes gh-34194
2025-01-04 18:27:05 +02:00
Sam Brannen 51b89743e1 Polishing 2025-01-04 18:12:13 +02:00
Sam Brannen 69ef885b68 Merge branch '6.2.x' 2025-01-04 15:59:47 +02:00
Sam Brannen 019f76468b Revise TestBeanForInheritanceIntegrationTests
Amongst other refinements, this commit ensures that the "anotherBean"
use case is actually tested.
2025-01-04 14:16:59 +02:00
Sam Brannen 087641c508 Merge branch '6.2.x' 2025-01-03 17:29:14 +02:00
Sam Brannen 0da4ae96b4 Rename internal MockitoBeans class to MockBeans
This is a prerequisite for gh-33925 which will introduce a public
@MockitoBeans container annotation in the same package.
2025-01-03 17:26:45 +02:00
Sam Brannen 2ba0022704 Polishing 2025-01-03 17:26:45 +02:00
Simon Baslé eb9ee9fafa Polishing
`@since` missing tags in some methods related to the HttpHeaders change
2024-12-27 12:14:23 +01:00
Simon Baslé f025d60b92 Merge branch '6.2.x' 2024-12-27 11:00:10 +01:00
Simon Baslé 0f38c28e91 Fix ServletRequestDataBinder ctor binding with `[]`-indexed query params
This change ensures that a request containing query parameters in the
array format `someArray[]=value` can be bound into a simple array in
constructors, even for cases where the array values don't have nested
properties.

The value resolver is directly called in the constructor case, before
any mutable properties are considered or even cleared (see
`WebDataBinder#adaptEmptyArrayIndices` method). As a result, we need to
accommodate the possibility that the request stores array elements under
the `name[]` key rather than `name`. This change attempts a secondary
lookup with the `[]` suffix if the type is a list or array, and the key
doesn't include an index.

Closes gh-34121
2024-12-27 10:59:15 +01:00
Simon Baslé 3505c4bcad Ensure DataBinder can bind constructor with a Map with simple values
This change ensures that DataBinder can bind constructor with a Map
parameter that has no nested properties, but just simple values like
a String: `someMap[0]=exampleString`.

Integration tests have been added to cover similar cases that use the
ServletRequestDataBinder.

Closes gh-34043
2024-12-27 10:57:30 +01:00
Sébastien Deleuze a442c180f1 Refine null-safety in the spring-test module
Closes gh-34161
2024-12-26 17:49:17 +01:00
Simon Baslé f24f9a4ba4 Polishing
Javadoc links to `HttpHeaders#remove` now use the new String-based
signature.

See gh-33913
2024-12-26 10:30:46 +01:00
Simon Baslé 0c6f5d7d29 `HttpHeaders` are no longer a `MultiValueMap`
This change removes the `MultiValueMap` nature of `HttpHeaders`, since
it inherits APIs that do not align well with underlying server
implementations. Notably, methods that allows to iterate over the whole
collection of headers are susceptible to artificially introduced
duplicates when multiple casings are used for a given header, depending
on the underlying implementation.

This change includes a dedicated key set implementation to support
iterator-based removal, and either keeps map method implementations that
are relevant or introduces header-focused methods that have a similar
responsibility (like `hasHeaderValues(String, List)` and
`containsHeaderValue(String, String)`).

In order to nudge users away from using an HttpHeaders as a Map, the
`asSingleValueMap` view is deprecated. In order to offer an escape
hatch to users that do make use of the `MultiValueMap` API, a similar
`asMultiValueMap` view is introduced but is immediately marked as
deprecated.

This change also adds map-like but header-focused assertions to
`HttpHeadersAssert`, since it cannot extend `AbstractMapAssert` anymore.

Closes gh-33913
2024-12-24 14:43:51 +01:00
rstoyanchev 373763723e Deprecate use of PathMatcher and UrlPathHelper in web
Closes gh-34018
2024-12-19 15:59:41 +00:00
Sébastien Deleuze 0e85d950b3 Remove unneeded `@NonNull` annotations
See gh-28797
2024-12-19 11:07:33 +01:00
Sébastien Deleuze bc5d771a06 Switch to JSpecify annotations
This commit updates the whole Spring Framework codebase to use JSpecify
annotations instead of Spring null-safety annotations with JSR 305
semantics.

JSpecify provides signficant enhancements such as properly defined
specifications, a canonical dependency with no split-package issue,
better tooling, better Kotlin integration and the capability to specify
generic type, array and varargs element null-safety. Generic type
null-safety is not defined by this commit yet and will be specified
later.

A key difference is that Spring null-safety annotations, following
JSR 305 semantics, apply to fields, parameters and return values,
while JSpecify annotations apply to type usages. That's why this
commit moves nullability annotations closer to the type for fields
and return values.

See gh-28797
2024-12-19 11:07:23 +01:00
rstoyanchev e9946937e7 Remove Spring MVC suffixPattern and trailingSlash matching
See gh-34036
2024-12-17 09:49:04 +00:00
Juergen Hoeller 5cbb5d4d70 Upgrade to Hibernate ORM 7.0.0.Beta3 and Validator 9.0.0.CR1
Using relocated Maven coordinates.

See gh-33750
2024-12-15 14:37:54 +01:00
Sam Brannen 01a15cf0e7 Merge branch '6.2.x' 2024-12-12 14:41:51 +01:00
Sam Brannen ea8b18fbc7 Polish Javadoc for BeanOverrideHandler 2024-12-12 14:41:23 +01:00
Brian Clozel 88a5b4efd3 Merge branch '6.2.x' 2024-12-11 16:12:01 +01:00
Brian Clozel 52006b71bc Support Servlet error message in MockMvc assertions
Prior to this commit, `MockMvc` would support checking for the Servlet
error message as the "response status reason". While this error message
can be driven with the `@ResponseStatus` annotation, this message is not
technically the HTTP status reason listed on the response status line.

This message is provided by the Servlet container in the error page when
the `response.sendError(int, String)` method is used.

This commit adds the missing
`mvc.get().uri("/error/message")).hasErrorMessage("error message")`
assertion to check for this Servlet error message.

Closes gh-34016
2024-12-11 16:00:41 +01:00
Sam Brannen 3256bf436a Merge branch '6.2.x' 2024-12-11 12:12:57 +01:00
Sam Brannen 7206b28272 Implement toString() in TestBeanOverrideHandler
Closes gh-34072
2024-12-11 12:12:35 +01:00
Sam Brannen 2d4baec2b1 Merge branch '6.2.x' 2024-12-10 12:52:32 +01:00
Sam Brannen 54948a4e88 Log warning when one Bean Override overrides another Bean Override
It is currently possible for one Bean Override to override another
logically equivalent Bean Override.

For example, a @⁠TestBean can override a @⁠MockitoBean, and vice versa.

In fact, it's also possible for a @⁠MockitoBean to override another
@⁠MockitoBean, for a @⁠TestBean to override a @⁠TestBean, etc.

However, there may be viable use cases for one override overriding
another override. For example, one may have a need to spy on a bean
created by a @⁠TestBean factory method.

In light of that, we do not prohibit one Bean Override from overriding
another Bean Override; however, with this commit we now log a warning
to help developers diagnose issues in case such an override is
unintentional.

For example, given the following test class, where TestConfig registers
a single bean of type MyService named "myService"...

@⁠SpringJUnitConfig(TestConfig.class)
class MyTests {

  @⁠TestBean(methodName = "example.TestUtils#createMyService")
  MyService testService;

  @⁠MockitoBean
  MyService mockService;

  @⁠Test
  void test() {
    // ...
  }
}

... running that test class results in a log message similar to the
following, which has been formatted for readability.

WARN - Bean with name 'myService' was overridden by multiple handlers:
[
 [TestBeanOverrideHandler@44b21f9f
  field = example.MyService example.MyTests.testService,
  beanType = example.MyService,
  beanName = [null],
  strategy = REPLACE_OR_CREATE
 ],
 [MockitoBeanOverrideHandler@7ee8130e
  field = example.MyService example.MyTests.mockService,
  beanType = example.MyService,
  beanName = [null],
  strategy = REPLACE_OR_CREATE,
  reset = AFTER,
  extraInterfaces = set[[empty]],
  answers = RETURNS_DEFAULTS, serializable = false
 ]
]

NOTE: The last registered BeanOverrideHandler wins. In the above
example, that means that @⁠MockitoBean overrides @⁠TestBean, resulting
in a Mockito mock for the MyService bean in the test's
ApplicationContext.

Closes gh-34056
2024-12-10 12:49:48 +01:00
Sam Brannen cd25a64ac0 Merge branch '6.2.x' 2024-12-09 16:01:07 +01:00
Sam Brannen cd60a0013b Reject identical Bean Overrides
Prior to this commit, the Bean Override feature in the Spring
TestContext Framework (for annotations such as @⁠MockitoBean and
@⁠TestBean) silently allowed one bean override to override another
"identical" bean override; however, Spring Boot's @⁠MockBean and
@⁠SpyBean support preemptively rejects identical overrides and throws
an IllegalStateException to signal the configuration error to the user.

To align with the behavior of @⁠MockBean and @⁠SpyBean in Spring Boot,
and to help developers avoid scenarios that are potentially confusing
or difficult to debug, this commit rejects identical bean overrides in
the Spring TestContext Framework.

Note, however, that it is still possible for a bean override to
override a logically equivalent bean override. For example, a
@⁠TestBean can override a @⁠MockitoBean, and vice versa.

Closes gh-34054
2024-12-09 16:00:24 +01:00
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