diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpoint.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpoint.java index 0e83b125aa..5b4374f48e 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpoint.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,9 @@ import org.springframework.core.env.Environment; * endpoint is considered available if it is both enabled and exposed on the specified * technologies. *

- * Matches enablement according to the endpoints specific {@link Environment} property, - * falling back to {@code management.endpoints.enabled-by-default} or failing that - * {@link Endpoint#enableByDefault()}. + * Matches access according to the endpoint's specific {@link Environment} property, + * falling back to {@code management.endpoints.default-access} or failing that + * {@link Endpoint#defaultAccess()}. *

* Matches exposure according to any of the {@code management.endpoints.web.exposure.} * or {@code management.endpoints.jmx.exposure.} specific properties or failing that diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java index 5659f895d9..817eef2c4d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.springframework.boot.actuate.autoconfigure.endpoint.condition; import java.util.Arrays; -import java.util.Collection; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.List; @@ -126,8 +125,7 @@ class OnAvailableEndpointCondition extends SpringBootCondition { private ConditionOutcome getAccessOutcome(Environment environment, MergedAnnotation endpointAnnotation, EndpointId endpointId, ConditionMessage.Builder message) { Access defaultAccess = endpointAnnotation.getEnum("defaultAccess", Access.class); - boolean enableByDefault = endpointAnnotation.getBoolean("enableByDefault"); - Access access = getAccess(environment, endpointId, (enableByDefault) ? defaultAccess : Access.NONE); + Access access = getAccess(environment, endpointId, defaultAccess); return new ConditionOutcome(access != Access.NONE, message.because("the configured access for endpoint '%s' is %s".formatted(endpointId, access))); } @@ -153,17 +151,8 @@ class OnAvailableEndpointCondition extends SpringBootCondition { private Set getExposures(MergedAnnotation conditionAnnotation) { EndpointExposure[] exposures = conditionAnnotation.getEnumArray("exposure", EndpointExposure.class); - return replaceCloudFoundryExposure( - (exposures.length == 0) ? EnumSet.allOf(EndpointExposure.class) : Arrays.asList(exposures)); - } - - @SuppressWarnings("removal") - private Set replaceCloudFoundryExposure(Collection exposures) { - Set result = EnumSet.copyOf(exposures); - if (result.remove(EndpointExposure.CLOUD_FOUNDRY)) { - result.add(EndpointExposure.WEB); - } - return result; + return (exposures.length == 0) ? EnumSet.allOf(EndpointExposure.class) + : EnumSet.copyOf(Arrays.asList(exposures)); } private Set getExposureOutcomeContributors(ConditionContext context) { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/EndpointExposure.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/EndpointExposure.java index 5d5bd55d41..a008680c4a 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/EndpointExposure.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/EndpointExposure.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,16 +32,7 @@ public enum EndpointExposure { /** * Exposed over a web endpoint. */ - WEB("health"), - - /** - * Exposed on Cloud Foundry over `/cloudfoundryapplication`. - * @since 2.6.4 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of using - * {@link EndpointExposure#WEB} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - CLOUD_FOUNDRY("*"); + WEB("health"); private final String[] defaultIncludes; diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java index c42b9cf575..6b868ff46f 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementWebServerFactoryCustomizer.java @@ -46,15 +46,6 @@ public class ManagementWebServerFactoryCustomizer>[] customizerClasses; - @SafeVarargs - @SuppressWarnings("varargs") - @Deprecated(since = "3.5.0", forRemoval = true) - protected ManagementWebServerFactoryCustomizer(ListableBeanFactory beanFactory, - Class>... customizerClasses) { - this.beanFactory = beanFactory; - this.customizerClasses = customizerClasses; - } - /** * Creates a new customizer that will retrieve beans using the given * {@code beanFactory}. diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java index 09b63a9824..efb0b44ff9 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/ConditionalOnAvailableEndpointTests.java @@ -273,21 +273,6 @@ class ConditionalOnAvailableEndpointTests { .isInstanceOf(MutuallyExclusiveConfigurationPropertiesException.class)); } - @Test - void whenDisabledAndAccessibleByDefaultEndpointIsNotAvailable() { - this.contextRunner.withUserConfiguration(DisabledButAccessibleEndpointConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=*") - .run((context) -> assertThat(context).doesNotHaveBean(DisabledButAccessibleEndpoint.class)); - } - - @Test - void whenDisabledAndAccessibleByDefaultEndpointCanBeAvailable() { - this.contextRunner.withUserConfiguration(DisabledButAccessibleEndpointConfiguration.class) - .withPropertyValues("management.endpoints.web.exposure.include=*", - "management.endpoints.access.default=unrestricted") - .run((context) -> assertThat(context).hasSingleBean(DisabledButAccessibleEndpoint.class)); - } - @Test @WithTestEndpointOutcomeExposureContributor void exposureOutcomeContributorCanMakeEndpointAvailable() { @@ -325,12 +310,6 @@ class ConditionalOnAvailableEndpointTests { } - @SuppressWarnings({ "deprecation", "removal" }) - @Endpoint(id = "disabledbutaccessible", enableByDefault = false) - static class DisabledButAccessibleEndpoint { - - } - @EndpointExtension(endpoint = SpringEndpoint.class, filter = TestFilter.class) static class SpringEndpointExtension { @@ -430,15 +409,4 @@ class ConditionalOnAvailableEndpointTests { } - @Configuration(proxyBeanMethods = false) - static class DisabledButAccessibleEndpointConfiguration { - - @Bean - @ConditionalOnAvailableEndpoint - DisabledButAccessibleEndpoint disabledButAccessible() { - return new DisabledButAccessibleEndpoint(); - } - - } - } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java index ab4f2fdefc..4cbbe08b3e 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/AbstractExposableEndpoint.java @@ -36,19 +36,6 @@ public abstract class AbstractExposableEndpoint implements private final List operations; - /** - * Create a new {@link AbstractExposableEndpoint} instance. - * @param id the endpoint id - * @param enabledByDefault if the endpoint is enabled by default - * @param operations the endpoint operations - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #AbstractExposableEndpoint(EndpointId, Access, Collection)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public AbstractExposableEndpoint(EndpointId id, boolean enabledByDefault, Collection operations) { - this(id, (enabledByDefault) ? Access.UNRESTRICTED : Access.READ_ONLY, operations); - } - /** * Create a new {@link AbstractExposableEndpoint} instance. * @param id the endpoint id @@ -69,13 +56,6 @@ public abstract class AbstractExposableEndpoint implements return this.id; } - @Override - @SuppressWarnings("removal") - @Deprecated(since = "3.4.0", forRemoval = true) - public boolean isEnableByDefault() { - return this.defaultAccess != Access.NONE; - } - @Override public Access getDefaultAccess() { return this.defaultAccess; diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ExposableEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ExposableEndpoint.java index 34f8dc6d95..5f5718b1e5 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ExposableEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/ExposableEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,15 +34,6 @@ public interface ExposableEndpoint { */ EndpointId getEndpointId(); - /** - * Returns if the endpoint is enabled by default. - * @return if the endpoint is enabled by default - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #getDefaultAccess()} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - boolean isEnableByDefault(); - /** * Returns the access to the endpoint that is permitted by default. * @return access that is permitted by default diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java index 95512c1b26..9e5d17210c 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/AbstractDiscoveredEndpoint.java @@ -41,23 +41,6 @@ public abstract class AbstractDiscoveredEndpoint extends Ab private final Object endpointBean; - /** - * Create a new {@link AbstractDiscoveredEndpoint} instance. - * @param discoverer the discoverer that discovered the endpoint - * @param endpointBean the primary source bean - * @param id the ID of the endpoint - * @param enabledByDefault if the endpoint is enabled by default - * @param operations the endpoint operations - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #AbstractDiscoveredEndpoint(EndpointDiscoverer, Object, EndpointId, Access, Collection)} - */ - @SuppressWarnings("removal") - @Deprecated(since = "3.4.0", forRemoval = true) - public AbstractDiscoveredEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { - this(discoverer, endpointBean, id, (enabledByDefault) ? Access.UNRESTRICTED : Access.READ_ONLY, operations); - } - /** * Create a new {@link AbstractDiscoveredEndpoint} instance. * @param discoverer the discoverer that discovered the endpoint diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/Endpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/Endpoint.java index d52fee56bf..6699cf3257 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/Endpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/Endpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,14 +63,6 @@ public @interface Endpoint { */ String id() default ""; - /** - * If the endpoint should be enabled or disabled by default. - * @return {@code true} if the endpoint is enabled by default - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of {@link #defaultAccess()} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - boolean enableByDefault() default true; - /** * Level of access to the endpoint that is permitted by default. * @return the default level of access diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java index 09b12e99d9..1fe6db636f 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java @@ -84,21 +84,6 @@ public abstract class EndpointDiscoverer, O exten private volatile Collection endpoints; - /** - * Create a new {@link EndpointDiscoverer} instance. - * @param applicationContext the source application context - * @param parameterValueMapper the parameter value mapper - * @param invokerAdvisors invoker advisors to apply - * @param endpointFilters endpoint filters to apply - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #EndpointDiscoverer(ApplicationContext, ParameterValueMapper, Collection, Collection, Collection)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public EndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, - Collection invokerAdvisors, Collection> endpointFilters) { - this(applicationContext, parameterValueMapper, invokerAdvisors, endpointFilters, Collections.emptyList()); - } - /** * Create a new {@link EndpointDiscoverer} instance. * @param applicationContext the source application context @@ -381,21 +366,6 @@ public abstract class EndpointDiscoverer, O exten return (Class) ResolvableType.forClass(EndpointDiscoverer.class, getClass()).resolveGeneric(0); } - /** - * Factory method called to create the {@link ExposableEndpoint endpoint}. - * @param endpointBean the source endpoint bean - * @param id the ID of the endpoint - * @param enabledByDefault if the endpoint is enabled by default - * @param operations the endpoint operations - * @return a created endpoint (a {@link DiscoveredEndpoint} is recommended) - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #createEndpoint(Object, EndpointId, Access, Collection)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - protected E createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, Collection operations) { - return createEndpoint(endpointBean, id, (enabledByDefault) ? Access.UNRESTRICTED : Access.NONE, operations); - } - /** * Factory method called to create the {@link ExposableEndpoint endpoint}. * @param endpointBean the source endpoint bean @@ -498,8 +468,7 @@ public abstract class EndpointDiscoverer, O exten this.beanType = beanType; this.beanSupplier = beanSupplier; this.id = EndpointId.of(environment, id); - boolean enabledByDefault = annotation.getBoolean("enableByDefault"); - this.defaultAccess = enabledByDefault ? annotation.getEnum("defaultAccess", Access.class) : Access.NONE; + this.defaultAccess = annotation.getEnum("defaultAccess", Access.class); this.filter = getFilter(beanType); } diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java index 795f39ae81..d091ac7f0b 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethod.java @@ -49,7 +49,7 @@ public class OperationMethod { * @param method the source method * @param operationType the operation type * @deprecated since 4.0.0 for removal in 4.2.0 in favor of - * {@link #OperationMethod(Method, OperationType, Predicate)}p + * {@link #OperationMethod(Method, OperationType, Predicate)} */ @Deprecated(since = "4.0.0", forRemoval = true) public OperationMethod(Method method, OperationType operationType) { diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpoint.java index 02916b5cdb..2e27ab17f8 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,15 +48,6 @@ public @interface JmxEndpoint { @AliasFor(annotation = Endpoint.class) String id() default ""; - /** - * If the endpoint should be enabled or disabled by default. - * @return {@code true} if the endpoint is enabled by default - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - */ - @Deprecated(since = "3.4.0", forRemoval = true) - @AliasFor(annotation = Endpoint.class) - boolean enableByDefault() default true; - /** * Level of access to the endpoint that is permitted by default. * @return the default level of access diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java index d9f235def8..f062859666 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.springframework.boot.actuate.endpoint.jmx.annotation; import java.util.Collection; -import java.util.Collections; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; @@ -48,22 +47,6 @@ import org.springframework.context.annotation.ImportRuntimeHints; public class JmxEndpointDiscoverer extends EndpointDiscoverer implements JmxEndpointsSupplier { - /** - * Create a new {@link JmxEndpointDiscoverer} instance. - * @param applicationContext the source application context - * @param parameterValueMapper the parameter value mapper - * @param invokerAdvisors invoker advisors to apply - * @param endpointFilters endpoint filters to apply - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #JmxEndpointDiscoverer(ApplicationContext, ParameterValueMapper, Collection, Collection, Collection)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public JmxEndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, - Collection invokerAdvisors, - Collection> endpointFilters) { - this(applicationContext, parameterValueMapper, invokerAdvisors, endpointFilters, Collections.emptyList()); - } - /** * Create a new {@link JmxEndpointDiscoverer} instance. * @param applicationContext the source application context diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpoint.java index 02aed521ae..da0c3f0927 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,13 +65,6 @@ public @interface ControllerEndpoint { @AliasFor(annotation = Endpoint.class) String id(); - /** - * If the endpoint should be enabled or disabled by default. - * @return {@code true} if the endpoint is enabled by default - */ - @AliasFor(annotation = Endpoint.class) - boolean enableByDefault() default true; - /** * Level of access to the endpoint that is permitted by default. * @return the default level of access diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RestControllerEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RestControllerEndpoint.java index 549f8e1a58..24d7419750 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RestControllerEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RestControllerEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,13 +67,6 @@ public @interface RestControllerEndpoint { @AliasFor(annotation = Endpoint.class) String id(); - /** - * If the endpoint should be enabled or disabled by default. - * @return {@code true} if the endpoint is enabled by default - */ - @AliasFor(annotation = Endpoint.class) - boolean enableByDefault() default true; - /** * Level of access to the endpoint that is permitted by default. * @return the default level of access diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpoint.java index ca1480015c..13e6334138 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,13 +58,6 @@ public @interface ServletEndpoint { @AliasFor(annotation = Endpoint.class) String id(); - /** - * If the endpoint should be enabled or disabled by default. - * @return {@code true} if the endpoint is enabled by default - */ - @AliasFor(annotation = Endpoint.class) - boolean enableByDefault() default true; - /** * Level of access to the endpoint that is permitted by default. * @return the default level of access diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpoint.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpoint.java index eb0f48ca6e..526635d1ce 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,15 +48,6 @@ public @interface WebEndpoint { @AliasFor(annotation = Endpoint.class) String id(); - /** - * If the endpoint should be enabled or disabled by default. - * @return {@code true} if the endpoint is enabled by default - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of {@link #defaultAccess()} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - @AliasFor(annotation = Endpoint.class) - boolean enableByDefault() default true; - /** * Level of access to the endpoint that is permitted by default. * @return the default level of access diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java index d984a3854f..6dae0a7863 100644 --- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java +++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,26 +59,6 @@ public class WebEndpointDiscoverer extends EndpointDiscoverer endpointPathMappers, - Collection invokerAdvisors, - Collection> filters) { - this(applicationContext, parameterValueMapper, endpointMediaTypes, endpointPathMappers, Collections.emptyList(), - invokerAdvisors, filters, Collections.emptyList()); - } - /** * Create a new {@link WebEndpointDiscoverer} instance. * @param applicationContext the source application context diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java index 2c3dc531f4..9b53eecb89 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java @@ -562,13 +562,6 @@ class EndpointDiscovererTests { return new TestExposableEndpoint(this, endpointBean, id, defaultAccess, operations); } - @Override - @SuppressWarnings("removal") - protected TestExposableEndpoint createEndpoint(Object endpointBean, EndpointId id, boolean enabledByDefault, - Collection operations) { - return new TestExposableEndpoint(this, endpointBean, id, enabledByDefault, operations); - } - @Override protected TestOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { @@ -603,13 +596,6 @@ class EndpointDiscovererTests { return new SpecializedExposableEndpoint(this, endpointBean, id, defaultAccess, operations); } - @Override - @SuppressWarnings("removal") - protected SpecializedExposableEndpoint createEndpoint(Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { - return new SpecializedExposableEndpoint(this, endpointBean, id, enabledByDefault, operations); - } - @Override protected SpecializedOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod, OperationInvoker invoker) { @@ -631,12 +617,6 @@ class EndpointDiscovererTests { super(discoverer, endpointBean, id, defaultAccess, operations); } - @SuppressWarnings("removal") - TestExposableEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { - super(discoverer, endpointBean, id, enabledByDefault, operations); - } - } static class SpecializedExposableEndpoint extends AbstractDiscoveredEndpoint { @@ -647,12 +627,6 @@ class EndpointDiscovererTests { super(discoverer, endpointBean, id, defaultAccess, operations); } - @SuppressWarnings("removal") - SpecializedExposableEndpoint(EndpointDiscoverer discoverer, Object endpointBean, EndpointId id, - boolean enabledByDefault, Collection operations) { - super(discoverer, endpointBean, id, enabledByDefault, operations); - } - } static class TestOperation extends AbstractDiscoveredOperation { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestExposableJmxEndpoint.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestExposableJmxEndpoint.java index 3d78ebb9c4..9f5970b52b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestExposableJmxEndpoint.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/TestExposableJmxEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,12 +44,6 @@ public class TestExposableJmxEndpoint implements ExposableJmxEndpoint { return EndpointId.of("test"); } - @Override - @SuppressWarnings("removal") - public boolean isEnableByDefault() { - return true; - } - @Override public Collection getOperations() { return this.operations; diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java index d48488aef0..2dcbc717a1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointLinksResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,7 +63,6 @@ class EndpointLinksResolverTests { operations.add(operationWithPath("/alpha/{name}", "alpha-name")); ExposableWebEndpoint endpoint = mock(ExposableWebEndpoint.class); given(endpoint.getEndpointId()).willReturn(EndpointId.of("alpha")); - given(endpoint.isEnableByDefault()).willReturn(true); given(endpoint.getOperations()).willReturn(operations); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(endpoint)) @@ -80,7 +79,6 @@ class EndpointLinksResolverTests { void resolvedLinksContainsALinkForServletEndpoint() { ExposableServletEndpoint servletEndpoint = mock(ExposableServletEndpoint.class); given(servletEndpoint.getEndpointId()).willReturn(EndpointId.of("alpha")); - given(servletEndpoint.isEnableByDefault()).willReturn(true); given(servletEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(servletEndpoint)) @@ -94,7 +92,6 @@ class EndpointLinksResolverTests { void resolvedLinksContainsALinkForControllerEndpoint() { ExposableControllerEndpoint controllerEndpoint = mock(ExposableControllerEndpoint.class); given(controllerEndpoint.getEndpointId()).willReturn(EndpointId.of("alpha")); - given(controllerEndpoint.isEnableByDefault()).willReturn(true); given(controllerEndpoint.getRootPath()).willReturn("alpha"); String requestUrl = "https://api.example.com/actuator"; Map links = new EndpointLinksResolver(Collections.singletonList(controllerEndpoint)) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java index 4ff371300b..11fe9b9a0a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionOutcome.java @@ -148,17 +148,4 @@ public class ConditionOutcome { return (this.message != null) ? this.message.toString() : ""; } - /** - * Return the inverse of the specified condition outcome. - * @param outcome the outcome to inverse - * @return the inverse of the condition outcome - * @since 1.3.0 - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #ConditionOutcome(boolean, ConditionMessage)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - public static ConditionOutcome inverse(ConditionOutcome outcome) { - return new ConditionOutcome(!outcome.isMatch(), outcome.getConditionMessage()); - } - } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/service/connection/ConnectionDetailsFactories.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/service/connection/ConnectionDetailsFactories.java index 5ec7c2deff..8bd16bd7c7 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/service/connection/ConnectionDetailsFactories.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/service/connection/ConnectionDetailsFactories.java @@ -48,16 +48,6 @@ public class ConnectionDetailsFactories { private final List> registrations = new ArrayList<>(); - /** - * Create a new {@link ConnectionDetailsFactories} instance. - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #ConnectionDetailsFactories(ClassLoader)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - public ConnectionDetailsFactories() { - this((ClassLoader) null); - } - /** * Create a new {@link ConnectionDetailsFactories} instance. * @param classLoader the class loader used to load factories diff --git a/spring-boot-project/spring-boot-batch/src/main/java/org/springframework/boot/batch/autoconfigure/JobLauncherApplicationRunner.java b/spring-boot-project/spring-boot-batch/src/main/java/org/springframework/boot/batch/autoconfigure/JobLauncherApplicationRunner.java index d897318e44..05346d61e9 100644 --- a/spring-boot-project/spring-boot-batch/src/main/java/org/springframework/boot/batch/autoconfigure/JobLauncherApplicationRunner.java +++ b/spring-boot-project/spring-boot-batch/src/main/java/org/springframework/boot/batch/autoconfigure/JobLauncherApplicationRunner.java @@ -120,11 +120,6 @@ public class JobLauncherApplicationRunner } } - @Deprecated(since = "3.0.10", forRemoval = true) - public void validate() { - afterPropertiesSet(); - } - public void setOrder(int order) { this.order = order; } diff --git a/spring-boot-project/spring-boot-cassandra/src/dockerTest/java/org/springframework/boot/cassandra/testcontainers/DeprecatedCassandraContainerConnectionDetailsFactoryTests.java b/spring-boot-project/spring-boot-cassandra/src/dockerTest/java/org/springframework/boot/cassandra/testcontainers/DeprecatedCassandraContainerConnectionDetailsFactoryTests.java deleted file mode 100644 index 4a2910b334..0000000000 --- a/spring-boot-project/spring-boot-cassandra/src/dockerTest/java/org/springframework/boot/cassandra/testcontainers/DeprecatedCassandraContainerConnectionDetailsFactoryTests.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.cassandra.testcontainers; - -import com.datastax.oss.driver.api.core.CqlSession; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.CassandraContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.cassandra.autoconfigure.CassandraAutoConfiguration; -import org.springframework.boot.cassandra.autoconfigure.CassandraConnectionDetails; -import org.springframework.boot.testcontainers.service.connection.ServiceConnection; -import org.springframework.boot.testsupport.container.TestImage; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link DeprecatedCassandraContainerConnectionDetailsFactory}. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SpringJUnitConfig -@Testcontainers(disabledWithoutDocker = true) -@Deprecated(since = "3.4.0", forRemoval = true) -class DeprecatedCassandraContainerConnectionDetailsFactoryTests { - - @Container - @ServiceConnection - static final CassandraContainer cassandra = TestImage.container(CassandraContainer.class); - - @Autowired(required = false) - private CassandraConnectionDetails connectionDetails; - - @Autowired - private CqlSession cqlSession; - - @Test - void connectionCanBeMadeToCassandraContainer() { - assertThat(this.connectionDetails).isNotNull(); - assertThat(this.cqlSession.getMetadata().getNodes()).hasSize(1); - } - - @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration(CassandraAutoConfiguration.class) - static class TestConfiguration { - - } - -} diff --git a/spring-boot-project/spring-boot-cassandra/src/main/java/org/springframework/boot/cassandra/testcontainers/DeprecatedCassandraContainerConnectionDetailsFactory.java b/spring-boot-project/spring-boot-cassandra/src/main/java/org/springframework/boot/cassandra/testcontainers/DeprecatedCassandraContainerConnectionDetailsFactory.java deleted file mode 100644 index b41a5390cd..0000000000 --- a/spring-boot-project/spring-boot-cassandra/src/main/java/org/springframework/boot/cassandra/testcontainers/DeprecatedCassandraContainerConnectionDetailsFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.cassandra.testcontainers; - -import java.net.InetSocketAddress; -import java.util.List; - -import org.testcontainers.containers.CassandraContainer; - -import org.springframework.boot.cassandra.autoconfigure.CassandraConnectionDetails; -import org.springframework.boot.ssl.SslBundle; -import org.springframework.boot.testcontainers.service.connection.ContainerConnectionDetailsFactory; -import org.springframework.boot.testcontainers.service.connection.ContainerConnectionSource; -import org.springframework.boot.testcontainers.service.connection.ServiceConnection; - -/** - * {@link ContainerConnectionDetailsFactory} to create {@link CassandraConnectionDetails} - * from a {@link ServiceConnection @ServiceConnection}-annotated - * {@link CassandraContainer}. - * - * @author Moritz Halbritter - * @author Andy Wilkinson - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link CassandraContainerConnectionDetailsFactory}. - */ -@Deprecated(since = "3.4.0", forRemoval = true) -class DeprecatedCassandraContainerConnectionDetailsFactory - extends ContainerConnectionDetailsFactory, CassandraConnectionDetails> { - - @Override - protected CassandraConnectionDetails getContainerConnectionDetails( - ContainerConnectionSource> source) { - return new CassandraContainerConnectionDetails(source); - } - - /** - * {@link CassandraConnectionDetails} backed by a {@link ContainerConnectionSource}. - */ - private static final class CassandraContainerConnectionDetails - extends ContainerConnectionDetails> implements CassandraConnectionDetails { - - private CassandraContainerConnectionDetails(ContainerConnectionSource> source) { - super(source); - } - - @Override - public List getContactPoints() { - InetSocketAddress contactPoint = getContainer().getContactPoint(); - return List.of(new Node(contactPoint.getHostString(), contactPoint.getPort())); - } - - @Override - public String getUsername() { - return getContainer().getUsername(); - } - - @Override - public String getPassword() { - return getContainer().getPassword(); - } - - @Override - public String getLocalDatacenter() { - return getContainer().getLocalDatacenter(); - } - - @Override - public SslBundle getSslBundle() { - return super.getSslBundle(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-cassandra/src/main/resources/META-INF/spring.factories b/spring-boot-project/spring-boot-cassandra/src/main/resources/META-INF/spring.factories index a534c7e898..feea7d785d 100644 --- a/spring-boot-project/spring-boot-cassandra/src/main/resources/META-INF/spring.factories +++ b/spring-boot-project/spring-boot-cassandra/src/main/resources/META-INF/spring.factories @@ -1,5 +1,4 @@ # Connection Details Factories org.springframework.boot.autoconfigure.service.connection.ConnectionDetailsFactory=\ org.springframework.boot.cassandra.docker.compose.CassandraDockerComposeConnectionDetailsFactory,\ -org.springframework.boot.cassandra.testcontainers.CassandraContainerConnectionDetailsFactory,\ -org.springframework.boot.cassandra.testcontainers.DeprecatedCassandraContainerConnectionDetailsFactory +org.springframework.boot.cassandra.testcontainers.CassandraContainerConnectionDetailsFactory diff --git a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java index bfa767badc..ad2518da5d 100644 --- a/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java +++ b/spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/OnEnabledDevToolsCondition.java @@ -27,12 +27,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; * A condition that checks if DevTools should be enabled. * * @author Madhura Bhave - * @since 2.2.0 - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link ConditionalOnEnabledDevTools @ConditionalOnEnabledDevTools} */ -@Deprecated(since = "3.5.0", forRemoval = true) -public class OnEnabledDevToolsCondition extends SpringBootCondition { +class OnEnabledDevToolsCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { diff --git a/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration.java b/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration.java index 747bf4deab..2d610c11be 100644 --- a/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration.java +++ b/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration.java @@ -278,8 +278,6 @@ public class FlywayAutoConfiguration { map.from(properties.isBaselineOnMigrate()) .to((baselineOnMigrate) -> configuration.baselineOnMigrate(baselineOnMigrate)); map.from(properties.isCleanDisabled()).to((cleanDisabled) -> configuration.cleanDisabled(cleanDisabled)); - map.from(properties.isCleanOnValidationError()) - .to((cleanOnValidationError) -> configuration.cleanOnValidationError(cleanOnValidationError)); map.from(properties.isGroup()).to((group) -> configuration.group(group)); map.from(properties.isMixed()).to((mixed) -> configuration.mixed(mixed)); map.from(properties.isOutOfOrder()).to((outOfOrder) -> configuration.outOfOrder(outOfOrder)); diff --git a/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayProperties.java b/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayProperties.java index 3ba5d5273f..c366eb75c6 100644 --- a/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayProperties.java +++ b/spring-boot-project/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayProperties.java @@ -28,7 +28,6 @@ import java.util.List; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; import org.springframework.boot.convert.DurationUnit; /** @@ -211,11 +210,6 @@ public class FlywayProperties { */ private boolean cleanDisabled = true; - /** - * Whether to automatically call clean when a validation error occurs. - */ - private boolean cleanOnValidationError; - /** * Whether to group all pending migrations together in the same transaction when * applying them. @@ -595,17 +589,6 @@ public class FlywayProperties { this.cleanDisabled = cleanDisabled; } - @Deprecated(since = "3.4.0", forRemoval = true) - @DeprecatedConfigurationProperty(since = "3.4.0", reason = "Deprecated in Flyway 10.18 and removed in Flyway 11.0") - public boolean isCleanOnValidationError() { - return this.cleanOnValidationError; - } - - @Deprecated(since = "3.4.0", forRemoval = true) - public void setCleanOnValidationError(boolean cleanOnValidationError) { - this.cleanOnValidationError = cleanOnValidationError; - } - public boolean isGroup() { return this.group; } @@ -718,39 +701,6 @@ public class FlywayProperties { this.errorOverrides = errorOverrides; } - @DeprecatedConfigurationProperty(replacement = "spring.flyway.oracle.sqlplus", since = "3.2.0") - @Deprecated(since = "3.2.0", forRemoval = true) - public Boolean getOracleSqlplus() { - return getOracle().getSqlplus(); - } - - @Deprecated(since = "3.2.0", forRemoval = true) - public void setOracleSqlplus(Boolean oracleSqlplus) { - getOracle().setSqlplus(oracleSqlplus); - } - - @DeprecatedConfigurationProperty(replacement = "spring.flyway.oracle.sqlplus-warn", since = "3.2.0") - @Deprecated(since = "3.2.0", forRemoval = true) - public Boolean getOracleSqlplusWarn() { - return getOracle().getSqlplusWarn(); - } - - @Deprecated(since = "3.2.0", forRemoval = true) - public void setOracleSqlplusWarn(Boolean oracleSqlplusWarn) { - getOracle().setSqlplusWarn(oracleSqlplusWarn); - } - - @DeprecatedConfigurationProperty(replacement = "spring.flyway.oracle.wallet-location", since = "3.2.0") - @Deprecated(since = "3.2.0", forRemoval = true) - public String getOracleWalletLocation() { - return getOracle().getWalletLocation(); - } - - @Deprecated(since = "3.2.0", forRemoval = true) - public void setOracleWalletLocation(String oracleWalletLocation) { - getOracle().setWalletLocation(oracleWalletLocation); - } - public Boolean getStream() { return this.stream; } @@ -775,17 +725,6 @@ public class FlywayProperties { this.kerberosConfigFile = kerberosConfigFile; } - @DeprecatedConfigurationProperty(replacement = "spring.flyway.oracle.kerberos-cache-file", since = "3.2.0") - @Deprecated(since = "3.2.0", forRemoval = true) - public String getOracleKerberosCacheFile() { - return getOracle().getKerberosCacheFile(); - } - - @Deprecated(since = "3.2.0", forRemoval = true) - public void setOracleKerberosCacheFile(String oracleKerberosCacheFile) { - getOracle().setKerberosCacheFile(oracleKerberosCacheFile); - } - public Boolean getOutputQueryResults() { return this.outputQueryResults; } @@ -794,17 +733,6 @@ public class FlywayProperties { this.outputQueryResults = outputQueryResults; } - @DeprecatedConfigurationProperty(replacement = "spring.flyway.sqlserver.kerberos-login-file") - @Deprecated(since = "3.2.0", forRemoval = true) - public String getSqlServerKerberosLoginFile() { - return getSqlserver().getKerberosLoginFile(); - } - - @Deprecated(since = "3.2.0", forRemoval = true) - public void setSqlServerKerberosLoginFile(String sqlServerKerberosLoginFile) { - getSqlserver().setKerberosLoginFile(sqlServerKerberosLoginFile); - } - public Boolean getSkipExecutingMigrations() { return this.skipExecutingMigrations; } diff --git a/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfigurationTests.java b/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfigurationTests.java index 79862f0d1f..8545efcd4a 100644 --- a/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfigurationTests.java @@ -643,19 +643,6 @@ class FlywayAutoConfigurationTests { } - @Test - @Deprecated(since = "3.2.0", forRemoval = true) - void oracleSqlplusIsCorrectlyMappedWithDeprecatedProperty() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-sqlplus=true") - .run((context) -> assertThat(context.getBean(Flyway.class) - .getConfiguration() - .getPluginRegister() - .getPlugin(OracleConfigurationExtension.class) - .getSqlplus()).isTrue()); - - } - @Test void oracleSqlplusWarnIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) @@ -667,18 +654,6 @@ class FlywayAutoConfigurationTests { .getSqlplusWarn()).isTrue()); } - @Test - @Deprecated(since = "3.2.0", forRemoval = true) - void oracleSqlplusWarnIsCorrectlyMappedWithDeprecatedProperty() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-sqlplus-warn=true") - .run((context) -> assertThat(context.getBean(Flyway.class) - .getConfiguration() - .getPluginRegister() - .getPlugin(OracleConfigurationExtension.class) - .getSqlplusWarn()).isTrue()); - } - @Test void oracleWallerLocationIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) @@ -690,18 +665,6 @@ class FlywayAutoConfigurationTests { .getWalletLocation()).isEqualTo("/tmp/my.wallet")); } - @Test - @Deprecated(since = "3.2.0", forRemoval = true) - void oracleWallerLocationIsCorrectlyMappedWithDeprecatedProperty() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-wallet-location=/tmp/my.wallet") - .run((context) -> assertThat(context.getBean(Flyway.class) - .getConfiguration() - .getPluginRegister() - .getPlugin(OracleConfigurationExtension.class) - .getWalletLocation()).isEqualTo("/tmp/my.wallet")); - } - @Test void oracleKerberosCacheFileIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) @@ -713,18 +676,6 @@ class FlywayAutoConfigurationTests { .getKerberosCacheFile()).isEqualTo("/tmp/cache")); } - @Test - @Deprecated(since = "3.2.0", forRemoval = true) - void oracleKerberosCacheFileIsCorrectlyMappedWithDeprecatedProperty() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.oracle-kerberos-cache-file=/tmp/cache") - .run((context) -> assertThat(context.getBean(Flyway.class) - .getConfiguration() - .getPluginRegister() - .getPlugin(OracleConfigurationExtension.class) - .getKerberosCacheFile()).isEqualTo("/tmp/cache")); - } - @Test void streamIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) @@ -835,20 +786,6 @@ class FlywayAutoConfigurationTests { .getFile()).isEqualTo("/tmp/config")); } - @Test - @Deprecated(since = "3.2.0", forRemoval = true) - void sqlServerKerberosLoginFileIsCorrectlyMappedWithDeprecatedProperty() { - this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) - .withPropertyValues("spring.flyway.sql-server-kerberos-login-file=/tmp/config") - .run((context) -> assertThat(context.getBean(Flyway.class) - .getConfiguration() - .getPluginRegister() - .getPlugin(SQLServerConfigurationExtension.class) - .getKerberos() - .getLogin() - .getFile()).isEqualTo("/tmp/config")); - } - @Test void skipExecutingMigrationsIsCorrectlyMapped() { this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class) diff --git a/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayPropertiesTests.java b/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayPropertiesTests.java index 6b09452fcd..b66c59f2cd 100644 --- a/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayPropertiesTests.java +++ b/spring-boot-project/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayPropertiesTests.java @@ -81,7 +81,6 @@ class FlywayPropertiesTests { assertThat(properties.getInitSqls()).isEmpty(); assertThat(properties.isBaselineOnMigrate()).isEqualTo(configuration.isBaselineOnMigrate()); assertThat(properties.isCleanDisabled()).isEqualTo(configuration.isCleanDisabled()); - assertThat(properties.isCleanOnValidationError()).isEqualTo(configuration.isCleanOnValidationError()); assertThat(properties.isGroup()).isEqualTo(configuration.isGroup()); assertThat(properties.isMixed()).isEqualTo(configuration.isMixed()); assertThat(properties.isOutOfOrder()).isEqualTo(configuration.isOutOfOrder()); @@ -111,9 +110,6 @@ class FlywayPropertiesTests { PropertyAccessorFactory.forBeanPropertyAccess(new ClassicConfiguration())); // Properties specific settings ignoreProperties(properties, "url", "driverClassName", "user", "password", "enabled"); - // Deprecated properties - ignoreProperties(properties, "oracleKerberosCacheFile", "oracleSqlplus", "oracleSqlplusWarn", - "oracleWalletLocation", "sqlServerKerberosLoginFile"); // Properties that are managed by specific extensions ignoreProperties(properties, "oracle", "postgresql", "sqlserver"); // Properties that are only used on the command line @@ -127,7 +123,7 @@ class FlywayPropertiesTests { ignoreProperties(configuration, "resolversAsClassNames", "callbacksAsClassNames", "driver", "modernConfig", "currentResolvedEnvironment", "reportFilename", "reportEnabled", "workingDirectory", "cachedDataSources", "cachedResolvedEnvironments", "currentEnvironmentName", "allEnvironments", - "environmentProvisionMode", "provisionMode"); + "environmentProvisionMode", "provisionMode", "cleanOnValidationError"); // Handled by the conversion service ignoreProperties(configuration, "baselineVersionAsString", "encodingAsString", "locationsAsStrings", "targetAsString"); diff --git a/spring-boot-project/spring-boot-graphql/src/main/java/org/springframework/boot/graphql/autoconfigure/GraphQlProperties.java b/spring-boot-project/spring-boot-graphql/src/main/java/org/springframework/boot/graphql/autoconfigure/GraphQlProperties.java index 7580a07ca7..27f535ac12 100644 --- a/spring-boot-project/spring-boot-graphql/src/main/java/org/springframework/boot/graphql/autoconfigure/GraphQlProperties.java +++ b/spring-boot-project/spring-boot-graphql/src/main/java/org/springframework/boot/graphql/autoconfigure/GraphQlProperties.java @@ -20,7 +20,6 @@ import java.time.Duration; import java.util.Arrays; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; import org.springframework.core.io.Resource; /** @@ -40,8 +39,6 @@ public class GraphQlProperties { private final Schema schema = new Schema(); - private final DeprecatedSse sse = new DeprecatedSse(this.http.getSse()); - private final Websocket websocket = new Websocket(); public Http getHttp() { @@ -52,17 +49,6 @@ public class GraphQlProperties { return this.graphiql; } - @DeprecatedConfigurationProperty(replacement = "spring.graphql.http.path", since = "3.5.0") - @Deprecated(since = "3.5.0", forRemoval = true) - public String getPath() { - return getHttp().getPath(); - } - - @Deprecated(since = "3.5.0", forRemoval = true) - public void setPath(String path) { - getHttp().setPath(path); - } - public Schema getSchema() { return this.schema; } @@ -75,10 +61,6 @@ public class GraphQlProperties { return this.rsocket; } - public DeprecatedSse getSse() { - return this.sse; - } - public static class Http { /** @@ -343,26 +325,4 @@ public class GraphQlProperties { } - @Deprecated(since = "3.5.1", forRemoval = true) - public static final class DeprecatedSse { - - private final Sse sse; - - private DeprecatedSse(Sse sse) { - this.sse = sse; - } - - @DeprecatedConfigurationProperty(replacement = "spring.graphql.http.sse.timeout", since = "3.5.0") - @Deprecated(since = "3.5.0", forRemoval = true) - public Duration getTimeout() { - return this.sse.getTimeout(); - } - - @Deprecated(since = "3.5.0", forRemoval = true) - public void setTimeout(Duration timeout) { - this.sse.setTimeout(timeout); - } - - } - } diff --git a/spring-boot-project/spring-boot-groovy-templates/src/test/java/org/springframework/boot/groovy/template/autoconfigure/GroovyTemplateAutoConfigurationTests.java b/spring-boot-project/spring-boot-groovy-templates/src/test/java/org/springframework/boot/groovy/template/autoconfigure/GroovyTemplateAutoConfigurationTests.java index bdaf19cc9d..ab19132c01 100644 --- a/spring-boot-project/spring-boot-groovy-templates/src/test/java/org/springframework/boot/groovy/template/autoconfigure/GroovyTemplateAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-groovy-templates/src/test/java/org/springframework/boot/groovy/template/autoconfigure/GroovyTemplateAutoConfigurationTests.java @@ -187,13 +187,6 @@ class GroovyTemplateAutoConfigurationTests { assertThat(writer.toString()).contains("Hello World"); } - @Test - @Deprecated(since = "3.5.0", forRemoval = true) - void customConfiguration() { - registerAndRefreshContext("spring.groovy.template.configuration.auto-indent:true"); - assertThat(this.context.getBean(GroovyMarkupConfigurer.class).isAutoIndent()).isTrue(); - } - @Test void enableAutoEscape() { registerAndRefreshContext("spring.groovy.template.auto-escape:true"); diff --git a/spring-boot-project/spring-boot-gson/src/main/java/org/springframework/boot/gson/autoconfigure/GsonProperties.java b/spring-boot-project/spring-boot-gson/src/main/java/org/springframework/boot/gson/autoconfigure/GsonProperties.java index d0f149c6d8..4ac8b7d517 100644 --- a/spring-boot-project/spring-boot-gson/src/main/java/org/springframework/boot/gson/autoconfigure/GsonProperties.java +++ b/spring-boot-project/spring-boot-gson/src/main/java/org/springframework/boot/gson/autoconfigure/GsonProperties.java @@ -21,7 +21,6 @@ import com.google.gson.Gson; import com.google.gson.LongSerializationPolicy; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; /** * Configuration properties to configure {@link Gson}. @@ -163,12 +162,6 @@ public class GsonProperties { this.strictness = strictness; } - @Deprecated(since = "3.4.0", forRemoval = true) - @DeprecatedConfigurationProperty(replacement = "spring.gson.strictness", since = "3.4.0") - public Boolean getLenient() { - return (this.strictness != null) && (this.strictness == Strictness.LENIENT); - } - public void setLenient(Boolean lenient) { setStrictness((lenient != null && lenient) ? Strictness.LENIENT : Strictness.STRICT); } diff --git a/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/Gson210AutoConfigurationTests.java b/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/Gson210AutoConfigurationTests.java index 433e15560f..23fa55ec2e 100644 --- a/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/Gson210AutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/Gson210AutoConfigurationTests.java @@ -46,33 +46,6 @@ class Gson210AutoConfigurationTests { }); } - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void withoutLenient() { - this.contextRunner.run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson).hasFieldOrPropertyWithValue("lenient", false); - }); - } - - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void withLenientTrue() { - this.contextRunner.withPropertyValues("spring.gson.lenient:true").run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson).hasFieldOrPropertyWithValue("lenient", true); - }); - } - - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void withLenientFalse() { - this.contextRunner.withPropertyValues("spring.gson.lenient:false").run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson).hasFieldOrPropertyWithValue("lenient", false); - }); - } - public class DataObject { @SuppressWarnings("unused") diff --git a/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/GsonAutoConfigurationTests.java b/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/GsonAutoConfigurationTests.java index 89f6b74788..4a874883c0 100644 --- a/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/GsonAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-gson/src/test/java/org/springframework/boot/gson/autoconfigure/GsonAutoConfigurationTests.java @@ -209,33 +209,6 @@ class GsonAutoConfigurationTests { }); } - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void withoutLenient() { - this.contextRunner.run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson).hasFieldOrPropertyWithValue("strictness", null); - }); - } - - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void withLenientTrue() { - this.contextRunner.withPropertyValues("spring.gson.lenient:true").run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson).hasFieldOrPropertyWithValue("strictness", Strictness.LENIENT); - }); - } - - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void withLenientFalse() { - this.contextRunner.withPropertyValues("spring.gson.lenient:false").run((context) -> { - Gson gson = context.getBean(Gson.class); - assertThat(gson).hasFieldOrPropertyWithValue("strictness", Strictness.STRICT); - }); - } - @Test void withoutStrictness() { this.contextRunner.run((context) -> { diff --git a/spring-boot-project/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/HikariCheckpointRestoreLifecycle.java b/spring-boot-project/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/HikariCheckpointRestoreLifecycle.java index 56cfe28ef1..b44289d818 100644 --- a/spring-boot-project/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/HikariCheckpointRestoreLifecycle.java +++ b/spring-boot-project/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/HikariCheckpointRestoreLifecycle.java @@ -75,20 +75,6 @@ public class HikariCheckpointRestoreLifecycle implements Lifecycle { private final ConfigurableApplicationContext applicationContext; - /** - * Creates a new {@code HikariCheckpointRestoreLifecycle} that will allow the given - * {@code dataSource} to participate in checkpoint-restore. The {@code dataSource} is - * {@link DataSourceUnwrapper#unwrap unwrapped} to a {@link HikariDataSource}. If such - * unwrapping is not possible, the lifecycle will have no effect. - * @param dataSource the checkpoint-restore participant - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #HikariCheckpointRestoreLifecycle(DataSource, ConfigurableApplicationContext)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public HikariCheckpointRestoreLifecycle(DataSource dataSource) { - this(dataSource, null); - } - /** * Creates a new {@code HikariCheckpointRestoreLifecycle} that will allow the given * {@code dataSource} to participate in checkpoint-restore. The {@code dataSource} is diff --git a/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/DefaultJmsListenerContainerFactoryConfigurer.java b/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/DefaultJmsListenerContainerFactoryConfigurer.java index fee743bd4c..21d1fcb99f 100644 --- a/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/DefaultJmsListenerContainerFactoryConfigurer.java +++ b/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/DefaultJmsListenerContainerFactoryConfigurer.java @@ -105,12 +105,8 @@ public final class DefaultJmsListenerContainerFactoryConfigurer { /** * Set the {@link ObservationRegistry} to use. * @param observationRegistry the {@link ObservationRegistry} - * @since 3.2.1 - * @deprecated since 3.3.10 for removal in 4.0.0 as this should have been package - * private */ - @Deprecated(since = "3.3.10", forRemoval = true) - public void setObservationRegistry(ObservationRegistry observationRegistry) { + void setObservationRegistry(ObservationRegistry observationRegistry) { this.observationRegistry = observationRegistry; } diff --git a/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/JmsProperties.java b/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/JmsProperties.java index 8e9723780a..b74dcc64c4 100644 --- a/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/JmsProperties.java +++ b/spring-boot-project/spring-boot-jms/src/main/java/org/springframework/boot/jms/autoconfigure/JmsProperties.java @@ -19,7 +19,6 @@ package org.springframework.boot.jms.autoconfigure; import java.time.Duration; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; /** * Configuration properties for JMS. @@ -203,28 +202,6 @@ public class JmsProperties { this.autoStartup = autoStartup; } - @Deprecated(since = "3.2.0", forRemoval = true) - @DeprecatedConfigurationProperty(replacement = "spring.jms.listener.session.acknowledge-mode", since = "3.2.0") - public AcknowledgeMode getAcknowledgeMode() { - return this.session.getAcknowledgeMode(); - } - - @Deprecated(since = "3.2.0", forRemoval = true) - public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) { - this.session.setAcknowledgeMode(acknowledgeMode); - } - - @DeprecatedConfigurationProperty(replacement = "spring.jms.listener.min-concurrency", since = "3.2.0") - @Deprecated(since = "3.2.0", forRemoval = true) - public Integer getConcurrency() { - return this.minConcurrency; - } - - @Deprecated(since = "3.2.0", forRemoval = true) - public void setConcurrency(Integer concurrency) { - this.minConcurrency = concurrency; - } - public Integer getMinConcurrency() { return this.minConcurrency; } diff --git a/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/EntityManagerFactoryBuilder.java b/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/EntityManagerFactoryBuilder.java index 103eac4cb6..89810cb0df 100644 --- a/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/EntityManagerFactoryBuilder.java +++ b/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/EntityManagerFactoryBuilder.java @@ -99,41 +99,6 @@ public class EntityManagerFactoryBuilder { this.persistenceUnitRootLocation = persistenceUnitRootLocation; } - /** - * Create a new instance passing in the common pieces that will be shared if multiple - * EntityManagerFactory instances are created. - * @param jpaVendorAdapter a vendor adapter - * @param jpaProperties the JPA properties to be passed to the persistence provider - * @param persistenceUnitManager optional source of persistence unit information (can - * be null) - * @deprecated since 3.4.4 for removal in 4.0.0 in favor of - * {@link #EntityManagerFactoryBuilder(JpaVendorAdapter, Function, PersistenceUnitManager)} - */ - @Deprecated(since = "3.4.4", forRemoval = true) - public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map jpaProperties, - PersistenceUnitManager persistenceUnitManager) { - this(jpaVendorAdapter, (datasource) -> jpaProperties, persistenceUnitManager, null); - } - - /** - * Create a new instance passing in the common pieces that will be shared if multiple - * EntityManagerFactory instances are created. - * @param jpaVendorAdapter a vendor adapter - * @param jpaProperties the JPA properties to be passed to the persistence provider - * @param persistenceUnitManager optional source of persistence unit information (can - * be null) - * @param persistenceUnitRootLocation the persistence unit root location to use as a - * fallback or {@code null} - * @since 1.4.1 - * @deprecated since 3.4.4 for removal in 4.0.0 in favor of - * {@link #EntityManagerFactoryBuilder(JpaVendorAdapter, Function, PersistenceUnitManager, URL)} - */ - @Deprecated(since = "3.4.4", forRemoval = true) - public EntityManagerFactoryBuilder(JpaVendorAdapter jpaVendorAdapter, Map jpaProperties, - PersistenceUnitManager persistenceUnitManager, URL persistenceUnitRootLocation) { - this(jpaVendorAdapter, (datasource) -> jpaProperties, persistenceUnitManager, persistenceUnitRootLocation); - } - /** * Create a new {@link Builder} for a {@code EntityManagerFactory} using the settings * of the given instance, and the given {@link DataSource}. diff --git a/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/autoconfigure/JpaBaseConfiguration.java b/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/autoconfigure/JpaBaseConfiguration.java index 8e4ac4ed2e..28e181647a 100644 --- a/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/autoconfigure/JpaBaseConfiguration.java +++ b/spring-boot-project/spring-boot-jpa/src/main/java/org/springframework/boot/jpa/autoconfigure/JpaBaseConfiguration.java @@ -156,17 +156,6 @@ public abstract class JpaBaseConfiguration { */ protected abstract Map getVendorProperties(DataSource dataSource); - /** - * Return the vendor-specific properties. - * @return the vendor properties - * @deprecated since 3.4.4 for removal in 4.0.0 in favor of - * {@link #getVendorProperties(DataSource)} - */ - @Deprecated(since = "3.4.4", forRemoval = true) - protected Map getVendorProperties() { - return getVendorProperties(getDataSource()); - } - /** * Customize vendor properties before they are used. Allows for post-processing (for * example to configure JTA specific settings). diff --git a/spring-boot-project/spring-boot-kafka/src/dockerTest/java/org/springframework/boot/kafka/testcontainers/DeprecatedConfluentKafkaContainerConnectionDetailsFactoryIntegrationTests.java b/spring-boot-project/spring-boot-kafka/src/dockerTest/java/org/springframework/boot/kafka/testcontainers/DeprecatedConfluentKafkaContainerConnectionDetailsFactoryIntegrationTests.java deleted file mode 100644 index 8bd1078822..0000000000 --- a/spring-boot-project/spring-boot-kafka/src/dockerTest/java/org/springframework/boot/kafka/testcontainers/DeprecatedConfluentKafkaContainerConnectionDetailsFactoryIntegrationTests.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.kafka.testcontainers; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; - -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.KafkaContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.kafka.autoconfigure.KafkaAutoConfiguration; -import org.springframework.boot.testcontainers.service.connection.ServiceConnection; -import org.springframework.boot.testsupport.container.TestImage; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.annotation.KafkaListener; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link DeprecatedConfluentKafkaContainerConnectionDetailsFactory}. - * - * @author Moritz Halbritter - * @author Andy Wilkinson - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SpringJUnitConfig -@Testcontainers(disabledWithoutDocker = true) -@TestPropertySource(properties = { "spring.kafka.consumer.group-id=test-group", - "spring.kafka.consumer.auto-offset-reset=earliest" }) -@Deprecated(since = "3.4.0", forRemoval = true) -class DeprecatedConfluentKafkaContainerConnectionDetailsFactoryIntegrationTests { - - @Container - @ServiceConnection - static final KafkaContainer kafka = TestImage.container(KafkaContainer.class); - - @Autowired - private KafkaTemplate kafkaTemplate; - - @Autowired - private TestListener listener; - - @Test - void connectionCanBeMadeToKafkaContainer() { - this.kafkaTemplate.send("test-topic", "test-data"); - Awaitility.waitAtMost(Duration.ofMinutes(4)) - .untilAsserted(() -> assertThat(this.listener.messages).containsExactly("test-data")); - } - - @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration(KafkaAutoConfiguration.class) - static class TestConfiguration { - - @Bean - TestListener testListener() { - return new TestListener(); - } - - } - - static class TestListener { - - private final List messages = new ArrayList<>(); - - @KafkaListener(topics = "test-topic") - void processMessage(String message) { - this.messages.add(message); - } - - } - -} diff --git a/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaConnectionDetails.java b/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaConnectionDetails.java index b015a45663..12dd746461 100644 --- a/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaConnectionDetails.java +++ b/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaConnectionDetails.java @@ -85,46 +85,6 @@ public interface KafkaConnectionDetails extends ConnectionDetails { return Configuration.of(getBootstrapServers(), getSslBundle(), getSecurityProtocol()); } - /** - * Returns the list of bootstrap servers used for consumers. - * @return the list of bootstrap servers used for consumers - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of {@link #getConsumer()} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - default List getConsumerBootstrapServers() { - return getConsumer().getBootstrapServers(); - } - - /** - * Returns the list of bootstrap servers used for producers. - * @return the list of bootstrap servers used for producers - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of {@link #getProducer()} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - default List getProducerBootstrapServers() { - return getProducer().getBootstrapServers(); - } - - /** - * Returns the list of bootstrap servers used for the admin. - * @return the list of bootstrap servers used for the admin - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of {@link #getAdmin()} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - default List getAdminBootstrapServers() { - return getAdmin().getBootstrapServers(); - } - - /** - * Returns the list of bootstrap servers used for Kafka Streams. - * @return the list of bootstrap servers used for Kafka Streams - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of {@link #getStreams()} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - default List getStreamsBootstrapServers() { - return getStreams().getBootstrapServers(); - } - /** * Kafka connection details configuration. */ diff --git a/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaProperties.java b/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaProperties.java index ac5c7db045..a7b6e144c9 100644 --- a/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaProperties.java +++ b/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/autoconfigure/KafkaProperties.java @@ -34,7 +34,6 @@ import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; import org.springframework.boot.context.properties.PropertyMapper; import org.springframework.boot.context.properties.source.MutuallyExclusiveConfigurationPropertiesException; import org.springframework.boot.convert.DurationUnit; @@ -1423,11 +1422,6 @@ public class KafkaProperties { this.protocol = protocol; } - @Deprecated(since = "3.2.0", forRemoval = true) - public Map buildProperties() { - return buildProperties(null); - } - public Map buildProperties(SslBundles sslBundles) { validate(); String bundleName = getBundle(); @@ -1619,51 +1613,6 @@ public class KafkaProperties { this.attempts = attempts; } - @DeprecatedConfigurationProperty(replacement = "spring.kafka.retry.topic.backoff.delay", since = "3.4.0") - @Deprecated(since = "3.4.0", forRemoval = true) - public Duration getDelay() { - return getBackoff().getDelay(); - } - - @Deprecated(since = "3.4.0", forRemoval = true) - public void setDelay(Duration delay) { - getBackoff().setDelay(delay); - } - - @DeprecatedConfigurationProperty(replacement = "spring.kafka.retry.topic.backoff.multiplier", - since = "3.4.0") - @Deprecated(since = "3.4.0", forRemoval = true) - public double getMultiplier() { - return getBackoff().getMultiplier(); - } - - @Deprecated(since = "3.4.0", forRemoval = true) - public void setMultiplier(double multiplier) { - getBackoff().setMultiplier(multiplier); - } - - @DeprecatedConfigurationProperty(replacement = "spring.kafka.retry.topic.backoff.maxDelay", since = "3.4.0") - @Deprecated(since = "3.4.0", forRemoval = true) - public Duration getMaxDelay() { - return getBackoff().getMaxDelay(); - } - - @Deprecated(since = "3.4.0", forRemoval = true) - public void setMaxDelay(Duration maxDelay) { - getBackoff().setMaxDelay(maxDelay); - } - - @DeprecatedConfigurationProperty(replacement = "spring.kafka.retry.topic.backoff.random", since = "3.4.0") - @Deprecated(since = "3.4.0", forRemoval = true) - public boolean isRandomBackOff() { - return getBackoff().isRandom(); - } - - @Deprecated(since = "3.4.0", forRemoval = true) - public void setRandomBackOff(boolean randomBackOff) { - getBackoff().setRandom(randomBackOff); - } - private final Backoff backoff = new Backoff(); public Backoff getBackoff() { diff --git a/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/testcontainers/DeprecatedConfluentKafkaContainerConnectionDetailsFactory.java b/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/testcontainers/DeprecatedConfluentKafkaContainerConnectionDetailsFactory.java deleted file mode 100644 index 8926ecb264..0000000000 --- a/spring-boot-project/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/testcontainers/DeprecatedConfluentKafkaContainerConnectionDetailsFactory.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.kafka.testcontainers; - -import java.util.List; - -import org.testcontainers.containers.KafkaContainer; - -import org.springframework.boot.kafka.autoconfigure.KafkaConnectionDetails; -import org.springframework.boot.ssl.SslBundle; -import org.springframework.boot.testcontainers.service.connection.ContainerConnectionDetailsFactory; -import org.springframework.boot.testcontainers.service.connection.ContainerConnectionSource; -import org.springframework.boot.testcontainers.service.connection.ServiceConnection; - -/** - * {@link ContainerConnectionDetailsFactory} to create {@link KafkaConnectionDetails} from - * a {@link ServiceConnection @ServiceConnection}-annotated {@link KafkaContainer}. - * - * @author Moritz Halbritter - * @author Andy Wilkinson - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link ConfluentKafkaContainerConnectionDetailsFactory}. - */ -@Deprecated(since = "3.4.0", forRemoval = true) -class DeprecatedConfluentKafkaContainerConnectionDetailsFactory - extends ContainerConnectionDetailsFactory { - - @Override - protected KafkaConnectionDetails getContainerConnectionDetails(ContainerConnectionSource source) { - return new ConfluentKafkaContainerConnectionDetails(source); - } - - /** - * {@link KafkaConnectionDetails} backed by a {@link ContainerConnectionSource}. - */ - private static final class ConfluentKafkaContainerConnectionDetails - extends ContainerConnectionDetails implements KafkaConnectionDetails { - - private ConfluentKafkaContainerConnectionDetails(ContainerConnectionSource source) { - super(source); - } - - @Override - public List getBootstrapServers() { - return List.of(getContainer().getBootstrapServers()); - } - - @Override - public SslBundle getSslBundle() { - return super.getSslBundle(); - } - - @Override - public String getSecurityProtocol() { - return (getSslBundle() != null) ? "SSL" : "PLAINTEXT"; - } - - } - -} diff --git a/spring-boot-project/spring-boot-kafka/src/main/resources/META-INF/spring.factories b/spring-boot-project/spring-boot-kafka/src/main/resources/META-INF/spring.factories index 25a983d8b3..4a30c0c82e 100644 --- a/spring-boot-project/spring-boot-kafka/src/main/resources/META-INF/spring.factories +++ b/spring-boot-project/spring-boot-kafka/src/main/resources/META-INF/spring.factories @@ -2,5 +2,4 @@ org.springframework.boot.autoconfigure.service.connection.ConnectionDetailsFactory=\ org.springframework.boot.kafka.testcontainers.ApacheKafkaContainerConnectionDetailsFactory,\ org.springframework.boot.kafka.testcontainers.ConfluentKafkaContainerConnectionDetailsFactory,\ -org.springframework.boot.kafka.testcontainers.DeprecatedConfluentKafkaContainerConnectionDetailsFactory,\ org.springframework.boot.kafka.testcontainers.RedpandaContainerConnectionDetailsFactory diff --git a/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationIntegrationTests.java index cf1dcb368b..3eaf55320e 100644 --- a/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationIntegrationTests.java @@ -103,8 +103,8 @@ class KafkaAutoConfigurationIntegrationTests { void testEndToEndWithRetryTopics() throws Exception { load(KafkaConfig.class, "spring.kafka.bootstrap-servers:" + getEmbeddedKafkaBrokersAsString(), "spring.kafka.consumer.group-id=testGroup", "spring.kafka.retry.topic.enabled=true", - "spring.kafka.retry.topic.attempts=5", "spring.kafka.retry.topic.delay=100ms", - "spring.kafka.retry.topic.multiplier=2", "spring.kafka.retry.topic.max-delay=300ms", + "spring.kafka.retry.topic.attempts=5", "spring.kafka.retry.topic.backoff.delay=100ms", + "spring.kafka.retry.topic.backoff.multiplier=2", "spring.kafka.retry.topic.backoff.max-delay=300ms", "spring.kafka.consumer.auto-offset-reset=earliest"); RetryTopicConfiguration configuration = this.context.getBean(RetryTopicConfiguration.class); assertThat(configuration.getDestinationTopicProperties()).extracting(DestinationTopic.Properties::delay) diff --git a/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationTests.java b/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationTests.java index da8e164fe9..0ad1f5f568 100644 --- a/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-kafka/src/test/java/org/springframework/boot/kafka/autoconfigure/KafkaAutoConfigurationTests.java @@ -566,22 +566,6 @@ class KafkaAutoConfigurationTests { }); } - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void retryTopicConfigurationWithExponentialBackOffUsingDeprecatedProperties() { - this.contextRunner.withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", - "spring.kafka.retry.topic.attempts=5", "spring.kafka.retry.topic.delay=100ms", - "spring.kafka.retry.topic.multiplier=2", "spring.kafka.retry.topic.max-delay=300ms") - .run((context) -> { - RetryTopicConfiguration configuration = context.getBean(RetryTopicConfiguration.class); - assertThat(configuration.getDestinationTopicProperties()).hasSize(5) - .extracting(DestinationTopic.Properties::delay, DestinationTopic.Properties::suffix) - .containsExactly(tuple(0L, ""), tuple(100L, "-retry-0"), tuple(200L, "-retry-1"), - tuple(300L, "-retry-2"), tuple(0L, "-dlt")); - }); - } - @Test void retryTopicConfigurationWithDefaultProperties() { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", @@ -607,18 +591,6 @@ class KafkaAutoConfigurationTests { .containsExactly(0L, 2000L, 0L))); } - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void retryTopicConfigurationWithFixedBackOffUsingDeprecatedProperties() { - this.contextRunner.withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", - "spring.kafka.retry.topic.attempts=4", "spring.kafka.retry.topic.delay=2s") - .run(assertRetryTopicConfiguration( - (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay) - .containsExactly(0L, 2000L, 0L))); - } - @Test void retryTopicConfigurationWithNoBackOff() { this.contextRunner.withPropertyValues("spring.application.name=my-test-app", @@ -630,18 +602,6 @@ class KafkaAutoConfigurationTests { .containsExactly(0L, 0L, 0L))); } - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void retryTopicConfigurationWithNoBackOffUsingDeprecatedProperties() { - this.contextRunner.withPropertyValues("spring.application.name=my-test-app", - "spring.kafka.bootstrap-servers=localhost:9092,localhost:9093", "spring.kafka.retry.topic.enabled=true", - "spring.kafka.retry.topic.attempts=4", "spring.kafka.retry.topic.delay=0") - .run(assertRetryTopicConfiguration( - (configuration) -> assertThat(configuration.getDestinationTopicProperties()).hasSize(3) - .extracting(DestinationTopic.Properties::delay) - .containsExactly(0L, 0L, 0L))); - } - private ContextConsumer assertRetryTopicConfiguration( Consumer configuration) { return (context) -> { diff --git a/spring-boot-project/spring-boot-metrics/src/test/java/org/springframework/boot/metrics/autoconfigure/export/otlp/OtlpMetricsPropertiesConfigAdapterTests.java b/spring-boot-project/spring-boot-metrics/src/test/java/org/springframework/boot/metrics/autoconfigure/export/otlp/OtlpMetricsPropertiesConfigAdapterTests.java index 0090a6b0e4..8754fbd03c 100644 --- a/spring-boot-project/spring-boot-metrics/src/test/java/org/springframework/boot/metrics/autoconfigure/export/otlp/OtlpMetricsPropertiesConfigAdapterTests.java +++ b/spring-boot-project/spring-boot-metrics/src/test/java/org/springframework/boot/metrics/autoconfigure/export/otlp/OtlpMetricsPropertiesConfigAdapterTests.java @@ -190,21 +190,21 @@ class OtlpMetricsPropertiesConfigAdapterTests { } @Test - void serviceGroupOverridesApplicationGroup() { + void serviceNamespaceOverridesApplicationGroup() { this.environment.setProperty("spring.application.group", "alpha"); - this.openTelemetryProperties.setResourceAttributes(Map.of("service.group", "beta")); - assertThat(createAdapter().resourceAttributes()).containsEntry("service.group", "beta"); + this.openTelemetryProperties.setResourceAttributes(Map.of("service.namespace", "beta")); + assertThat(createAdapter().resourceAttributes()).containsEntry("service.namespace", "beta"); } @Test - void shouldUseApplicationGroupIfServiceGroupIsNotSet() { + void shouldUseApplicationGroupIfServiceNamspaceIsNotSet() { this.environment.setProperty("spring.application.group", "alpha"); - assertThat(createAdapter().resourceAttributes()).containsEntry("service.group", "alpha"); + assertThat(createAdapter().resourceAttributes()).containsEntry("service.namespace", "alpha"); } @Test void shouldUseDefaultApplicationGroupIfApplicationGroupIsNotSet() { - assertThat(createAdapter().resourceAttributes()).doesNotContainKey("service.group"); + assertThat(createAdapter().resourceAttributes()).doesNotContainKey("service.namespace"); } private OtlpMetricsPropertiesConfigAdapter createAdapter() { diff --git a/spring-boot-project/spring-boot-mongodb/src/main/java/org/springframework/boot/mongodb/autoconfigure/StandardMongoClientSettingsBuilderCustomizer.java b/spring-boot-project/spring-boot-mongodb/src/main/java/org/springframework/boot/mongodb/autoconfigure/StandardMongoClientSettingsBuilderCustomizer.java index 5a81c3d835..1b917afdf3 100644 --- a/spring-boot-project/spring-boot-mongodb/src/main/java/org/springframework/boot/mongodb/autoconfigure/StandardMongoClientSettingsBuilderCustomizer.java +++ b/spring-boot-project/spring-boot-mongodb/src/main/java/org/springframework/boot/mongodb/autoconfigure/StandardMongoClientSettingsBuilderCustomizer.java @@ -49,25 +49,6 @@ public class StandardMongoClientSettingsBuilderCustomizer implements MongoClient private int order = 0; - /** - * Create a new instance. - * @param connectionString the connection string - * @param uuidRepresentation the uuid representation - * @param ssl the ssl properties - * @param sslBundles the ssl bundles - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #StandardMongoClientSettingsBuilderCustomizer(MongoConnectionDetails, UuidRepresentation)} - */ - @Deprecated(forRemoval = true, since = "3.5.0") - public StandardMongoClientSettingsBuilderCustomizer(ConnectionString connectionString, - UuidRepresentation uuidRepresentation, MongoProperties.Ssl ssl, SslBundles sslBundles) { - this.connectionDetails = null; - this.connectionString = connectionString; - this.uuidRepresentation = uuidRepresentation; - this.ssl = ssl; - this.sslBundles = sslBundles; - } - public StandardMongoClientSettingsBuilderCustomizer(MongoConnectionDetails connectionDetails, UuidRepresentation uuidRepresentation) { this.connectionString = null; diff --git a/spring-boot-project/spring-boot-opentelemetry/src/main/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributes.java b/spring-boot-project/spring-boot-opentelemetry/src/main/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributes.java index f7e900c11e..a30bc20d18 100644 --- a/spring-boot-project/spring-boot-opentelemetry/src/main/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributes.java +++ b/spring-boot-project/spring-boot-opentelemetry/src/main/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributes.java @@ -98,7 +98,6 @@ public class OpenTelemetryResourceAttributes { } }); attributes.computeIfAbsent("service.name", (key) -> getApplicationName()); - attributes.computeIfAbsent("service.group", (key) -> getApplicationGroup()); attributes.computeIfAbsent("service.namespace", (key) -> getServiceNamespace()); attributes.forEach(consumer); } @@ -107,17 +106,6 @@ public class OpenTelemetryResourceAttributes { return this.environment.getProperty("spring.application.name", DEFAULT_SERVICE_NAME); } - /** - * Returns the application group. - * @return the application group - * @deprecated since 3.5.0 for removal in 4.0.0 - */ - @Deprecated(since = "3.5.0", forRemoval = true) - private String getApplicationGroup() { - String applicationGroup = this.environment.getProperty("spring.application.group"); - return (StringUtils.hasLength(applicationGroup)) ? applicationGroup : null; - } - private String getServiceNamespace() { return this.environment.getProperty("spring.application.group"); } diff --git a/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributesTests.java b/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributesTests.java index a6484c969f..214190ecf0 100644 --- a/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributesTests.java +++ b/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetryResourceAttributesTests.java @@ -159,11 +159,10 @@ class OpenTelemetryResourceAttributesTests { } @Test - void springApplicationGroupNameShouldBeUsedAsDefaultServiceGroup() { + void springApplicationGroupNameShouldBeUsedAsDefaultServiceNamespace() { this.environment.setProperty("spring.application.group", "spring-boot"); - assertThat(getAttributes()).hasSize(3) + assertThat(getAttributes()).hasSize(2) .containsEntry("service.name", "unknown_service") - .containsEntry("service.group", "spring-boot") .containsEntry("service.namespace", "spring-boot"); } @@ -212,28 +211,26 @@ class OpenTelemetryResourceAttributesTests { void resourceAttributesShouldTakePrecedenceOverApplicationGroupNameForPopulatingServiceNamespace() { this.resourceAttributes.put("service.namespace", "spring-boot-app"); this.environment.setProperty("spring.application.group", "overridden"); - assertThat(getAttributes()).hasSize(3) + assertThat(getAttributes()).hasSize(2) .containsEntry("service.name", "unknown_service") - .containsEntry("service.group", "overridden") .containsEntry("service.namespace", "spring-boot-app"); } @Test void otelResourceAttributesShouldTakePrecedenceOverSpringApplicationGroupName() { - this.environmentVariables.put("OTEL_RESOURCE_ATTRIBUTES", "service.group=spring-boot"); + this.environmentVariables.put("OTEL_RESOURCE_ATTRIBUTES", "service.namespace=spring-boot"); this.environment.setProperty("spring.application.group", "spring-boot-app"); - assertThat(getAttributes()).hasSize(3) + assertThat(getAttributes()).hasSize(2) .containsEntry("service.name", "unknown_service") - .containsEntry("service.group", "spring-boot") - .containsEntry("service.namespace", "spring-boot-app"); + .containsEntry("service.namespace", "spring-boot"); } @Test void otelResourceAttributesShouldTakePrecedenceOverSpringApplicationGroupNameForServiceNamespace() { this.environmentVariables.put("OTEL_RESOURCE_ATTRIBUTES", "service.namespace=spring-boot"); this.environment.setProperty("spring.application.group", "overridden"); - assertThat(getAttributes()).hasSize(3) - .containsEntry("service.group", "overridden") + assertThat(getAttributes()).hasSize(2) + .containsEntry("service.name", "unknown_service") .containsEntry("service.namespace", "spring-boot"); } diff --git a/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetrySdkAutoConfigurationTests.java b/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetrySdkAutoConfigurationTests.java index 4ac62f6a7e..9c9e322a51 100644 --- a/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetrySdkAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetrySdkAutoConfigurationTests.java @@ -123,15 +123,6 @@ class OpenTelemetrySdkAutoConfigurationTests { }); } - @Test - void whenHasApplicationGroupPropertyProvidesServiceGroupResourceAttribute() { - this.contextRunner.withPropertyValues("spring.application.group=my-group").run((context) -> { - Resource resource = context.getBean(Resource.class); - assertThat(resource.getAttributes().asMap()) - .contains(entry(AttributeKey.stringKey("service.group"), "my-group")); - }); - } - @Test void whenHasApplicationGroupPropertyProvidesServiceNamespaceResourceAttribute() { this.contextRunner.withPropertyValues("spring.application.group=my-group").run((context) -> { diff --git a/spring-boot-project/spring-boot-restclient/src/main/java/org/springframework/boot/restclient/RestTemplateBuilder.java b/spring-boot-project/spring-boot-restclient/src/main/java/org/springframework/boot/restclient/RestTemplateBuilder.java index a34f146c69..aabb94e964 100644 --- a/spring-boot-project/spring-boot-restclient/src/main/java/org/springframework/boot/restclient/RestTemplateBuilder.java +++ b/spring-boot-project/spring-boot-restclient/src/main/java/org/springframework/boot/restclient/RestTemplateBuilder.java @@ -446,19 +446,6 @@ public class RestTemplateBuilder { this.defaultHeaders, this.customizers, this.requestCustomizers); } - /** - * Sets the connection timeout on the underlying {@link ClientHttpRequestFactory}. - * @param connectTimeout the connection timeout - * @return a new builder instance. - * @since 2.1.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #connectTimeout(Duration)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public RestTemplateBuilder setConnectTimeout(Duration connectTimeout) { - return connectTimeout(connectTimeout); - } - /** * Sets the connection timeout on the underlying {@link ClientHttpRequestFactory}. * @param connectTimeout the connection timeout @@ -472,19 +459,6 @@ public class RestTemplateBuilder { this.defaultHeaders, this.customizers, this.requestCustomizers); } - /** - * Sets the read timeout on the underlying {@link ClientHttpRequestFactory}. - * @param readTimeout the read timeout - * @return a new builder instance. - * @since 2.1.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #readTimeout(Duration)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public RestTemplateBuilder setReadTimeout(Duration readTimeout) { - return readTimeout(readTimeout); - } - /** * Sets the read timeout on the underlying {@link ClientHttpRequestFactory}. * @param readTimeout the read timeout @@ -511,19 +485,6 @@ public class RestTemplateBuilder { this.customizers, this.requestCustomizers); } - /** - * Sets the SSL bundle on the underlying {@link ClientHttpRequestFactory}. - * @param sslBundle the SSL bundle - * @return a new builder instance - * @since 3.1.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #sslBundle(SslBundle)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public RestTemplateBuilder setSslBundle(SslBundle sslBundle) { - return sslBundle(sslBundle); - } - /** * Sets the SSL bundle on the underlying {@link ClientHttpRequestFactory}. * @param sslBundle the SSL bundle diff --git a/spring-boot-project/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/SecurityProperties.java b/spring-boot-project/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/SecurityProperties.java index 4557e55939..04a0b80a12 100644 --- a/spring-boot-project/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/SecurityProperties.java +++ b/spring-boot-project/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/SecurityProperties.java @@ -47,15 +47,6 @@ public class SecurityProperties { */ public static final int BASIC_AUTH_ORDER = Ordered.LOWEST_PRECEDENCE - 5; - /** - * Order applied to the {@code WebSecurityCustomizer} that ignores standard static - * resource paths. - * @deprecated since 3.5.0 for removal in 4.0.0 since Spring Security no longer - * recommends using the {@code .ignoring()} method - */ - @Deprecated(since = "3.5.0", forRemoval = true) - public static final int IGNORED_ORDER = Ordered.HIGHEST_PRECEDENCE; - /** * Default order of Spring Security's Filter in the servlet container (i.e. amongst * other filters registered with the container). There is no connection between this diff --git a/spring-boot-project/spring-boot-test-autoconfigure/build.gradle b/spring-boot-project/spring-boot-test-autoconfigure/build.gradle index 89dab045f0..b9e1b6b112 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/build.gradle +++ b/spring-boot-project/spring-boot-test-autoconfigure/build.gradle @@ -19,6 +19,8 @@ dependencies { api(project(":spring-boot-project:spring-boot")) api(project(":spring-boot-project:spring-boot-autoconfigure")) api(project(":spring-boot-project:spring-boot-test")) + + compileOnly("org.mockito:mockito-core") dockerTestImplementation(project(":spring-boot-project:spring-boot-data-mongodb")) dockerTestImplementation(project(":spring-boot-project:spring-boot-docker-compose")) diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/ConditionReportApplicationContextFailureProcessor.java b/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/ConditionReportApplicationContextFailureProcessor.java deleted file mode 100644 index 1735c7671d..0000000000 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/ConditionReportApplicationContextFailureProcessor.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.autoconfigure; - -import org.springframework.boot.autoconfigure.condition.ConditionEvaluationReport; -import org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportMessage; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.ApplicationContextFailureProcessor; - -/** - * An {@link ApplicationContextFailureProcessor} that prints the - * {@link ConditionEvaluationReport} when the context cannot be prepared. - * - * @author Phillip Webb - * @author Scott Frederick - * @since 3.0.0 - * @deprecated in 3.2.11 for removal in 4.0.0 - */ -@Deprecated(since = "3.2.11", forRemoval = true) -public class ConditionReportApplicationContextFailureProcessor implements ApplicationContextFailureProcessor { - - @Override - public void processLoadFailure(ApplicationContext context, Throwable exception) { - if (context instanceof ConfigurableApplicationContext configurableContext) { - ConditionEvaluationReport report = ConditionEvaluationReport.get(configurableContext.getBeanFactory()); - System.err.println(new ConditionEvaluationReportMessage(report)); - } - } - -} diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/ConditionReportApplicationContextFailureProcessorTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/ConditionReportApplicationContextFailureProcessorTests.java deleted file mode 100644 index ec1c6fefc9..0000000000 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/ConditionReportApplicationContextFailureProcessorTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.autoconfigure; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration; -import org.springframework.boot.test.system.CapturedOutput; -import org.springframework.boot.test.system.OutputCaptureExtension; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Configuration; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link ConditionReportApplicationContextFailureProcessor}. - * - * @author Phillip Webb - * @author Scott Frederick - * @deprecated since 3.2.11 for removal in 4.0.0 - */ -@ExtendWith(OutputCaptureExtension.class) -@Deprecated(since = "3.2.11", forRemoval = true) -@SuppressWarnings("removal") -class ConditionReportApplicationContextFailureProcessorTests { - - @Test - void loadFailureShouldPrintReport(CapturedOutput output) { - SpringApplication application = new SpringApplication(TestConfig.class); - application.setWebApplicationType(WebApplicationType.NONE); - ConfigurableApplicationContext applicationContext = application.run(); - ConditionReportApplicationContextFailureProcessor processor = new ConditionReportApplicationContextFailureProcessor(); - processor.processLoadFailure(applicationContext, new IllegalStateException()); - assertThat(output).contains("CONDITIONS EVALUATION REPORT") - .contains("Positive matches") - .contains("Negative matches"); - } - - @Configuration(proxyBeanMethods = false) - @ImportAutoConfiguration(JacksonAutoConfiguration.class) - static class TestConfig { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java index 41b2523375..e7339d3855 100644 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java +++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunner.java @@ -110,26 +110,10 @@ import org.springframework.util.CollectionUtils; */ public abstract class AbstractApplicationContextRunner, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider> { - private static final Class[] NO_ADDITIONAL_CONTEXT_INTERFACES = {}; - private final RunnerConfiguration runnerConfiguration; private final Function, SELF> instanceFactory; - /** - * Create a new {@link AbstractApplicationContextRunner} instance. - * @param contextFactory the factory used to create the actual context - * @param instanceFactory the factory used to create new instance of the runner - * @since 2.6.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #AbstractApplicationContextRunner(Function, Supplier, Class...)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - protected AbstractApplicationContextRunner(Supplier contextFactory, - Function, SELF> instanceFactory) { - this(instanceFactory, contextFactory, NO_ADDITIONAL_CONTEXT_INTERFACES); - } - /** * Create a new {@link AbstractApplicationContextRunner} instance. * @param instanceFactory the factory used to create new instance of the runner diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java deleted file mode 100644 index 4a0446b02b..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/Definition.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.springframework.util.ObjectUtils; - -/** - * Base class for {@link MockDefinition} and {@link SpyDefinition}. - * - * @author Phillip Webb - * @see DefinitionsParser - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -abstract class Definition { - - private static final int MULTIPLIER = 31; - - private final String name; - - private final MockReset reset; - - private final boolean proxyTargetAware; - - private final QualifierDefinition qualifier; - - Definition(String name, MockReset reset, boolean proxyTargetAware, QualifierDefinition qualifier) { - this.name = name; - this.reset = (reset != null) ? reset : MockReset.AFTER; - this.proxyTargetAware = proxyTargetAware; - this.qualifier = qualifier; - } - - /** - * Return the name for bean. - * @return the name or {@code null} - */ - String getName() { - return this.name; - } - - /** - * Return the mock reset mode. - * @return the reset mode - */ - MockReset getReset() { - return this.reset; - } - - /** - * Return if AOP advised beans should be proxy target aware. - * @return if proxy target aware - */ - boolean isProxyTargetAware() { - return this.proxyTargetAware; - } - - /** - * Return the qualifier or {@code null}. - * @return the qualifier - */ - QualifierDefinition getQualifier() { - return this.qualifier; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || !getClass().isAssignableFrom(obj.getClass())) { - return false; - } - Definition other = (Definition) obj; - boolean result = true; - result = result && ObjectUtils.nullSafeEquals(this.name, other.name); - result = result && ObjectUtils.nullSafeEquals(this.reset, other.reset); - result = result && ObjectUtils.nullSafeEquals(this.proxyTargetAware, other.proxyTargetAware); - result = result && ObjectUtils.nullSafeEquals(this.qualifier, other.qualifier); - return result; - } - - @Override - public int hashCode() { - int result = 1; - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.name); - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.reset); - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.proxyTargetAware); - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.qualifier); - return result; - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java deleted file mode 100644 index 53ce986778..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Field; -import java.lang.reflect.TypeVariable; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import org.springframework.core.ResolvableType; -import org.springframework.core.annotation.MergedAnnotation; -import org.springframework.core.annotation.MergedAnnotations; -import org.springframework.core.annotation.MergedAnnotations.SearchStrategy; -import org.springframework.util.Assert; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; - -/** - * Parser to create {@link MockDefinition} and {@link SpyDefinition} instances from - * {@link MockBean @MockBean} and {@link SpyBean @SpyBean} annotations declared on or in a - * class. - * - * @author Phillip Webb - * @author Stephane Nicoll - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class DefinitionsParser { - - private final Set definitions; - - private final Map definitionFields; - - DefinitionsParser() { - this(Collections.emptySet()); - } - - DefinitionsParser(Collection existing) { - this.definitions = new LinkedHashSet<>(); - this.definitionFields = new LinkedHashMap<>(); - if (existing != null) { - this.definitions.addAll(existing); - } - } - - void parse(Class source) { - parseElement(source, null); - ReflectionUtils.doWithFields(source, (element) -> parseElement(element, source)); - } - - private void parseElement(AnnotatedElement element, Class source) { - MergedAnnotations annotations = MergedAnnotations.from(element, SearchStrategy.SUPERCLASS); - annotations.stream(MockBean.class) - .map(MergedAnnotation::synthesize) - .forEach((annotation) -> parseMockBeanAnnotation(annotation, element, source)); - annotations.stream(SpyBean.class) - .map(MergedAnnotation::synthesize) - .forEach((annotation) -> parseSpyBeanAnnotation(annotation, element, source)); - } - - private void parseMockBeanAnnotation(MockBean annotation, AnnotatedElement element, Class source) { - Set typesToMock = getOrDeduceTypes(element, annotation.value(), source); - Assert.state(!typesToMock.isEmpty(), () -> "Unable to deduce type to mock from " + element); - if (StringUtils.hasLength(annotation.name())) { - Assert.state(typesToMock.size() == 1, "The name attribute can only be used when mocking a single class"); - } - for (ResolvableType typeToMock : typesToMock) { - MockDefinition definition = new MockDefinition(annotation.name(), typeToMock, annotation.extraInterfaces(), - annotation.answer(), annotation.serializable(), annotation.reset(), - QualifierDefinition.forElement(element)); - addDefinition(element, definition, "mock"); - } - } - - private void parseSpyBeanAnnotation(SpyBean annotation, AnnotatedElement element, Class source) { - Set typesToSpy = getOrDeduceTypes(element, annotation.value(), source); - Assert.state(!typesToSpy.isEmpty(), () -> "Unable to deduce type to spy from " + element); - if (StringUtils.hasLength(annotation.name())) { - Assert.state(typesToSpy.size() == 1, "The name attribute can only be used when spying a single class"); - } - for (ResolvableType typeToSpy : typesToSpy) { - SpyDefinition definition = new SpyDefinition(annotation.name(), typeToSpy, annotation.reset(), - annotation.proxyTargetAware(), QualifierDefinition.forElement(element)); - addDefinition(element, definition, "spy"); - } - } - - private void addDefinition(AnnotatedElement element, Definition definition, String type) { - boolean isNewDefinition = this.definitions.add(definition); - Assert.state(isNewDefinition, () -> "Duplicate " + type + " definition " + definition); - if (element instanceof Field field) { - this.definitionFields.put(definition, field); - } - } - - private Set getOrDeduceTypes(AnnotatedElement element, Class[] value, Class source) { - Set types = new LinkedHashSet<>(); - for (Class type : value) { - types.add(ResolvableType.forClass(type)); - } - if (types.isEmpty() && element instanceof Field field) { - types.add((field.getGenericType() instanceof TypeVariable) ? ResolvableType.forField(field, source) - : ResolvableType.forField(field)); - } - return types; - } - - Set getDefinitions() { - return Collections.unmodifiableSet(this.definitions); - } - - Field getField(Definition definition) { - return this.definitionFields.get(definition); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockBean.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockBean.java deleted file mode 100644 index c8f8b251b5..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockBean.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Repeatable; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.runner.RunWith; -import org.mockito.Answers; -import org.mockito.MockSettings; - -import org.springframework.context.ApplicationContext; -import org.springframework.core.annotation.AliasFor; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * Annotation that can be used to add mocks to a Spring {@link ApplicationContext}. Can be - * used as a class level annotation or on fields in either {@code @Configuration} classes, - * or test classes that are {@link RunWith @RunWith} the {@link SpringRunner}. - *

- * Mocks can be registered by type or by {@link #name() bean name}. When registered by - * type, any existing single bean of a matching type (including subclasses) in the context - * will be replaced by the mock. When registered by name, an existing bean can be - * specifically targeted for replacement by a mock. In either case, if no existing bean is - * defined a new one will be added. Dependencies that are known to the application context - * but are not beans (such as those - * {@link org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerResolvableDependency(Class, Object) - * registered directly}) will not be found and a mocked bean will be added to the context - * alongside the existing dependency. - *

- * When {@code @MockBean} is used on a field, as well as being registered in the - * application context, the mock will also be injected into the field. Typical usage might - * be:

- * @RunWith(SpringRunner.class)
- * public class ExampleTests {
- *
- *     @MockBean
- *     private ExampleService service;
- *
- *     @Autowired
- *     private UserOfService userOfService;
- *
- *     @Test
- *     public void testUserOfService() {
- *         given(this.service.greet()).willReturn("Hello");
- *         String actual = this.userOfService.makeUse();
- *         assertEquals("Was: Hello", actual);
- *     }
- *
- *     @Configuration
- *     @Import(UserOfService.class) // A @Component injected with ExampleService
- *     static class Config {
- *     }
- *
- *
- * }
- * 
If there is more than one bean of the requested type, qualifier metadata must be - * specified at field level:
- * @RunWith(SpringRunner.class)
- * public class ExampleTests {
- *
- *     @MockBean
- *     @Qualifier("example")
- *     private ExampleService service;
- *
- *     ...
- * }
- * 
- *

- * This annotation is {@code @Repeatable} and may be specified multiple times when working - * with Java 8 or contained within an {@link MockBeans @MockBeans} annotation. - * - * @author Phillip Webb - * @since 1.4.0 - * @see MockitoPostProcessor - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link org.springframework.test.context.bean.override.mockito.MockitoBean} - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@Target({ ElementType.TYPE, ElementType.FIELD }) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Repeatable(MockBeans.class) -public @interface MockBean { - - /** - * The name of the bean to register or replace. If not specified the name will either - * be generated or, if the mock replaces an existing bean, the existing name will be - * used. - * @return the name of the bean - */ - String name() default ""; - - /** - * The classes to mock. This is an alias of {@link #classes()} which can be used for - * brevity if no other attributes are defined. See {@link #classes()} for details. - * @return the classes to mock - */ - @AliasFor("classes") - Class[] value() default {}; - - /** - * The classes to mock. Each class specified here will result in a mock being created - * and registered with the application context. Classes can be omitted when the - * annotation is used on a field. - *

- * When {@code @MockBean} also defines a {@code name} this attribute can only contain - * a single value. - *

- * If this is the only specified attribute consider using the {@code value} alias - * instead. - * @return the classes to mock - */ - @AliasFor("value") - Class[] classes() default {}; - - /** - * Any extra interfaces that should also be declared on the mock. See - * {@link MockSettings#extraInterfaces(Class...)} for details. - * @return any extra interfaces - */ - Class[] extraInterfaces() default {}; - - /** - * The {@link Answers} type to use on the mock. - * @return the answer type - */ - Answers answer() default Answers.RETURNS_DEFAULTS; - - /** - * If the generated mock is serializable. See {@link MockSettings#serializable()} for - * details. - * @return if the mock is serializable - */ - boolean serializable() default false; - - /** - * The reset mode to apply to the mock bean. The default is {@link MockReset#AFTER} - * meaning that mocks are automatically reset after each test method is invoked. - * @return the reset mode - */ - MockReset reset() default MockReset.AFTER; - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockBeans.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockBeans.java deleted file mode 100644 index 499b8cf8be..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockBeans.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Container annotation that aggregates several {@link MockBean @MockBean} annotations. - *

- * Can be used natively, declaring several nested {@link MockBean @MockBean} annotations. - * Can also be used in conjunction with Java 8's support for repeatable - * annotations, where {@link MockBean @MockBean} can simply be declared several times - * on the same {@linkplain ElementType#TYPE type}, implicitly generating this container - * annotation. - * - * @author Phillip Webb - * @since 1.4.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link org.springframework.test.context.bean.override.mockito.MockitoBean} - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@Documented -public @interface MockBeans { - - /** - * Return the contained {@link MockBean @MockBean} annotations. - * @return the mock beans - */ - MockBean[] value(); - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java deleted file mode 100644 index 60deee22ff..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockDefinition.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.mockito.Answers; -import org.mockito.MockSettings; - -import org.springframework.core.ResolvableType; -import org.springframework.core.style.ToStringCreator; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -import static org.mockito.Mockito.mock; - -/** - * A complete definition that can be used to create a Mockito mock. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockDefinition extends Definition { - - private static final int MULTIPLIER = 31; - - private final ResolvableType typeToMock; - - private final Set> extraInterfaces; - - private final Answers answer; - - private final boolean serializable; - - MockDefinition(String name, ResolvableType typeToMock, Class[] extraInterfaces, Answers answer, - boolean serializable, MockReset reset, QualifierDefinition qualifier) { - super(name, reset, false, qualifier); - Assert.notNull(typeToMock, "'typeToMock' must not be null"); - this.typeToMock = typeToMock; - this.extraInterfaces = asClassSet(extraInterfaces); - this.answer = (answer != null) ? answer : Answers.RETURNS_DEFAULTS; - this.serializable = serializable; - } - - private Set> asClassSet(Class[] classes) { - Set> classSet = new LinkedHashSet<>(); - if (classes != null) { - classSet.addAll(Arrays.asList(classes)); - } - return Collections.unmodifiableSet(classSet); - } - - /** - * Return the type that should be mocked. - * @return the type to mock; never {@code null} - */ - ResolvableType getTypeToMock() { - return this.typeToMock; - } - - /** - * Return the extra interfaces. - * @return the extra interfaces or an empty set - */ - Set> getExtraInterfaces() { - return this.extraInterfaces; - } - - /** - * Return the answers mode. - * @return the answers mode; never {@code null} - */ - Answers getAnswer() { - return this.answer; - } - - /** - * Return if the mock is serializable. - * @return if the mock is serializable - */ - boolean isSerializable() { - return this.serializable; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || obj.getClass() != getClass()) { - return false; - } - MockDefinition other = (MockDefinition) obj; - boolean result = super.equals(obj); - result = result && ObjectUtils.nullSafeEquals(this.typeToMock, other.typeToMock); - result = result && ObjectUtils.nullSafeEquals(this.extraInterfaces, other.extraInterfaces); - result = result && ObjectUtils.nullSafeEquals(this.answer, other.answer); - result = result && this.serializable == other.serializable; - return result; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.typeToMock); - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.extraInterfaces); - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.answer); - result = MULTIPLIER * result + Boolean.hashCode(this.serializable); - return result; - } - - @Override - public String toString() { - return new ToStringCreator(this).append("name", getName()) - .append("typeToMock", this.typeToMock) - .append("extraInterfaces", this.extraInterfaces) - .append("answer", this.answer) - .append("serializable", this.serializable) - .append("reset", getReset()) - .toString(); - } - - T createMock() { - return createMock(getName()); - } - - @SuppressWarnings("unchecked") - T createMock(String name) { - MockSettings settings = MockReset.withSettings(getReset()); - if (StringUtils.hasLength(name)) { - settings.name(name); - } - if (!this.extraInterfaces.isEmpty()) { - settings.extraInterfaces(ClassUtils.toClassArray(this.extraInterfaces)); - } - settings.defaultAnswer(this.answer); - if (this.serializable) { - settings.serializable(); - } - return (T) mock(this.typeToMock.resolve(), settings); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java deleted file mode 100644 index aa6894de77..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockReset.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.List; - -import org.mockito.MockSettings; -import org.mockito.MockingDetails; -import org.mockito.Mockito; -import org.mockito.listeners.InvocationListener; -import org.mockito.listeners.MethodInvocationReport; -import org.mockito.mock.MockCreationSettings; - -import org.springframework.util.Assert; - -/** - * Reset strategy used on a mock bean. Usually applied to a mock through the - * {@link MockBean @MockBean} annotation but can also be directly applied to any mock in - * the {@code ApplicationContext} using the static methods. - * - * @author Phillip Webb - * @since 1.4.0 - * @see ResetMocksTestExecutionListener - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link org.springframework.test.context.bean.override.mockito.MockReset} - */ -@Deprecated(since = "3.4.0", forRemoval = true) -public enum MockReset { - - /** - * Reset the mock before the test method runs. - */ - BEFORE, - - /** - * Reset the mock after the test method runs. - */ - AFTER, - - /** - * Don't reset the mock. - */ - NONE; - - /** - * Create {@link MockSettings settings} to be used with mocks where reset should occur - * before each test method runs. - * @return mock settings - */ - public static MockSettings before() { - return withSettings(BEFORE); - } - - /** - * Create {@link MockSettings settings} to be used with mocks where reset should occur - * after each test method runs. - * @return mock settings - */ - public static MockSettings after() { - return withSettings(AFTER); - } - - /** - * Create {@link MockSettings settings} to be used with mocks where a specific reset - * should occur. - * @param reset the reset type - * @return mock settings - */ - public static MockSettings withSettings(MockReset reset) { - return apply(reset, Mockito.withSettings()); - } - - /** - * Apply {@link MockReset} to existing {@link MockSettings settings}. - * @param reset the reset type - * @param settings the settings - * @return the configured settings - */ - public static MockSettings apply(MockReset reset, MockSettings settings) { - Assert.notNull(settings, "'settings' must not be null"); - if (reset != null && reset != NONE) { - settings.invocationListeners(new ResetInvocationListener(reset)); - } - return settings; - } - - /** - * Get the {@link MockReset} associated with the given mock. - * @param mock the source mock - * @return the reset type (never {@code null}) - */ - static MockReset get(Object mock) { - MockReset reset = MockReset.NONE; - MockingDetails mockingDetails = Mockito.mockingDetails(mock); - if (mockingDetails.isMock()) { - MockCreationSettings settings = mockingDetails.getMockCreationSettings(); - List listeners = settings.getInvocationListeners(); - for (Object listener : listeners) { - if (listener instanceof ResetInvocationListener resetInvocationListener) { - reset = resetInvocationListener.getReset(); - } - } - } - return reset; - } - - /** - * Dummy {@link InvocationListener} used to hold the {@link MockReset} value. - */ - private static class ResetInvocationListener implements InvocationListener { - - private final MockReset reset; - - ResetInvocationListener(MockReset reset) { - this.reset = reset; - } - - MockReset getReset() { - return this.reset; - } - - @Override - public void reportInvocation(MethodInvocationReport methodInvocationReport) { - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoBeans.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoBeans.java deleted file mode 100644 index d1f201e092..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoBeans.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * Beans created using Mockito. - * - * @author Andy Wilkinson - */ -class MockitoBeans implements Iterable { - - private final List beans = new ArrayList<>(); - - void add(Object bean) { - this.beans.add(bean); - } - - @Override - public Iterator iterator() { - return this.beans.iterator(); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java deleted file mode 100644 index e28bdc4962..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizer.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.LinkedHashSet; -import java.util.Set; - -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.ContextCustomizer; -import org.springframework.test.context.MergedContextConfiguration; - -/** - * A {@link ContextCustomizer} to add Mockito support. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockitoContextCustomizer implements ContextCustomizer { - - private final Set definitions; - - MockitoContextCustomizer(Set definitions) { - this.definitions = new LinkedHashSet<>(definitions); - } - - @Override - public void customizeContext(ConfigurableApplicationContext context, - MergedContextConfiguration mergedContextConfiguration) { - if (context instanceof BeanDefinitionRegistry registry) { - MockitoPostProcessor.register(registry, this.definitions); - } - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || obj.getClass() != getClass()) { - return false; - } - MockitoContextCustomizer other = (MockitoContextCustomizer) obj; - return this.definitions.equals(other.definitions); - } - - @Override - public int hashCode() { - return this.definitions.hashCode(); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactory.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactory.java deleted file mode 100644 index 44f993d8aa..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.List; - -import org.springframework.test.context.ContextConfigurationAttributes; -import org.springframework.test.context.ContextCustomizer; -import org.springframework.test.context.ContextCustomizerFactory; -import org.springframework.test.context.TestContextAnnotationUtils; - -/** - * A {@link ContextCustomizerFactory} to add Mockito support. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockitoContextCustomizerFactory implements ContextCustomizerFactory { - - @Override - public ContextCustomizer createContextCustomizer(Class testClass, - List configAttributes) { - // We gather the explicit mock definitions here since they form part of the - // MergedContextConfiguration key. Different mocks need to have a different key. - DefinitionsParser parser = new DefinitionsParser(); - parseDefinitions(testClass, parser); - return new MockitoContextCustomizer(parser.getDefinitions()); - } - - private void parseDefinitions(Class testClass, DefinitionsParser parser) { - parser.parse(testClass); - if (TestContextAnnotationUtils.searchEnclosingClass(testClass)) { - parseDefinitions(testClass.getEnclosingClass(), parser); - } - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java deleted file mode 100644 index 6218330b74..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessor.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.aop.scope.ScopedProxyUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.PropertyValues; -import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanFactoryUtils; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.NoUniqueBeanDefinitionException; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.config.ConstructorArgumentValues; -import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder; -import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; -import org.springframework.beans.factory.config.RuntimeBeanReference; -import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanNameGenerator; -import org.springframework.beans.factory.support.DefaultBeanNameGenerator; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.ConfigurationClassPostProcessor; -import org.springframework.core.Conventions; -import org.springframework.core.Ordered; -import org.springframework.core.PriorityOrdered; -import org.springframework.core.ResolvableType; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; - -/** - * A {@link BeanFactoryPostProcessor} used to register and inject - * {@link MockBean @MockBeans} with the {@link ApplicationContext}. An initial set of - * definitions can be passed to the processor with additional definitions being - * automatically created from {@code @Configuration} classes that use - * {@link MockBean @MockBean}. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @author Stephane Nicoll - * @author Andreas Neiser - * @since 1.4.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of Spring Framework's - * {@link MockitoBean} and {@link MockitoSpyBean} support - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0") -public class MockitoPostProcessor implements InstantiationAwareBeanPostProcessor, BeanClassLoaderAware, - BeanFactoryAware, BeanFactoryPostProcessor, Ordered { - - private static final String BEAN_NAME = MockitoPostProcessor.class.getName(); - - private static final String CONFIGURATION_CLASS_ATTRIBUTE = Conventions - .getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass"); - - private static final BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator(); - - private final Set definitions; - - private ClassLoader classLoader; - - private BeanFactory beanFactory; - - private final MockitoBeans mockitoBeans = new MockitoBeans(); - - private final Map beanNameRegistry = new HashMap<>(); - - private final Map fieldRegistry = new HashMap<>(); - - private final Map spies = new HashMap<>(); - - /** - * Create a new {@link MockitoPostProcessor} instance with the given initial - * definitions. - * @param definitions the initial definitions - */ - public MockitoPostProcessor(Set definitions) { - this.definitions = definitions; - } - - @Override - public void setBeanClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - Assert.isTrue(beanFactory instanceof ConfigurableListableBeanFactory, - "'beanFactory' must be a ConfigurableListableBeanFactory"); - this.beanFactory = beanFactory; - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - Assert.isTrue(beanFactory instanceof BeanDefinitionRegistry, "'beanFactory' must be a BeanDefinitionRegistry"); - postProcessBeanFactory(beanFactory, (BeanDefinitionRegistry) beanFactory); - } - - private void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) { - beanFactory.registerSingleton(MockitoBeans.class.getName(), this.mockitoBeans); - DefinitionsParser parser = new DefinitionsParser(this.definitions); - for (Class configurationClass : getConfigurationClasses(beanFactory)) { - parser.parse(configurationClass); - } - Set definitions = parser.getDefinitions(); - for (Definition definition : definitions) { - Field field = parser.getField(definition); - register(beanFactory, registry, definition, field); - } - } - - private Set> getConfigurationClasses(ConfigurableListableBeanFactory beanFactory) { - Set> configurationClasses = new LinkedHashSet<>(); - for (BeanDefinition beanDefinition : getConfigurationBeanDefinitions(beanFactory).values()) { - configurationClasses.add(ClassUtils.resolveClassName(beanDefinition.getBeanClassName(), this.classLoader)); - } - return configurationClasses; - } - - private Map getConfigurationBeanDefinitions(ConfigurableListableBeanFactory beanFactory) { - Map definitions = new LinkedHashMap<>(); - for (String beanName : beanFactory.getBeanDefinitionNames()) { - BeanDefinition definition = beanFactory.getBeanDefinition(beanName); - if (definition.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE) != null) { - definitions.put(beanName, definition); - } - } - return definitions; - } - - private void register(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, - Definition definition, Field field) { - if (definition instanceof MockDefinition mockDefinition) { - registerMock(beanFactory, registry, mockDefinition, field); - } - else if (definition instanceof SpyDefinition spyDefinition) { - registerSpy(beanFactory, registry, spyDefinition, field); - } - } - - private void registerMock(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, - MockDefinition definition, Field field) { - RootBeanDefinition beanDefinition = createBeanDefinition(definition); - String beanName = getBeanName(beanFactory, registry, definition, beanDefinition); - String transformedBeanName = BeanFactoryUtils.transformedBeanName(beanName); - if (registry.containsBeanDefinition(transformedBeanName)) { - BeanDefinition existing = registry.getBeanDefinition(transformedBeanName); - copyBeanDefinitionDetails(existing, beanDefinition); - registry.removeBeanDefinition(transformedBeanName); - } - registry.registerBeanDefinition(transformedBeanName, beanDefinition); - Object mock = definition.createMock(beanName + " bean"); - beanFactory.registerSingleton(transformedBeanName, mock); - this.mockitoBeans.add(mock); - this.beanNameRegistry.put(definition, beanName); - if (field != null) { - this.fieldRegistry.put(field, beanName); - } - } - - private RootBeanDefinition createBeanDefinition(MockDefinition mockDefinition) { - RootBeanDefinition definition = new RootBeanDefinition(mockDefinition.getTypeToMock().resolve()); - definition.setTargetType(mockDefinition.getTypeToMock()); - if (mockDefinition.getQualifier() != null) { - mockDefinition.getQualifier().applyTo(definition); - } - return definition; - } - - private String getBeanName(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, - MockDefinition mockDefinition, RootBeanDefinition beanDefinition) { - if (StringUtils.hasLength(mockDefinition.getName())) { - return mockDefinition.getName(); - } - Set existingBeans = getExistingBeans(beanFactory, mockDefinition.getTypeToMock(), - mockDefinition.getQualifier()); - if (existingBeans.isEmpty()) { - return MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry); - } - if (existingBeans.size() == 1) { - return existingBeans.iterator().next(); - } - String primaryCandidate = determinePrimaryCandidate(registry, existingBeans, mockDefinition.getTypeToMock()); - if (primaryCandidate != null) { - return primaryCandidate; - } - throw new IllegalStateException("Unable to register mock bean " + mockDefinition.getTypeToMock() - + " expected a single matching bean to replace but found " + existingBeans); - } - - private void copyBeanDefinitionDetails(BeanDefinition from, RootBeanDefinition to) { - to.setPrimary(from.isPrimary()); - } - - private void registerSpy(ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry, - SpyDefinition spyDefinition, Field field) { - Set existingBeans = getExistingBeans(beanFactory, spyDefinition.getTypeToSpy(), - spyDefinition.getQualifier()); - if (ObjectUtils.isEmpty(existingBeans)) { - createSpy(registry, spyDefinition, field); - } - else { - registerSpies(registry, spyDefinition, field, existingBeans); - } - } - - private Set getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type, - QualifierDefinition qualifier) { - Set candidates = new TreeSet<>(); - for (String candidate : getExistingBeans(beanFactory, type)) { - if (qualifier == null || qualifier.matches(beanFactory, candidate)) { - candidates.add(candidate); - } - } - return candidates; - } - - private Set getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType resolvableType) { - Set beans = new LinkedHashSet<>( - Arrays.asList(beanFactory.getBeanNamesForType(resolvableType, true, false))); - Class type = resolvableType.resolve(Object.class); - for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class, true, false)) { - beanName = BeanFactoryUtils.transformedBeanName(beanName); - Class producedType = beanFactory.getType(beanName, false); - if (type.equals(producedType)) { - beans.add(beanName); - } - } - beans.removeIf(this::isScopedTarget); - return beans; - } - - private boolean isScopedTarget(String beanName) { - try { - return ScopedProxyUtils.isScopedTarget(beanName); - } - catch (Throwable ex) { - return false; - } - } - - private void createSpy(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field) { - RootBeanDefinition beanDefinition = new RootBeanDefinition(spyDefinition.getTypeToSpy().resolve()); - String beanName = MockitoPostProcessor.beanNameGenerator.generateBeanName(beanDefinition, registry); - registry.registerBeanDefinition(beanName, beanDefinition); - registerSpy(spyDefinition, field, beanName); - } - - private void registerSpies(BeanDefinitionRegistry registry, SpyDefinition spyDefinition, Field field, - Collection existingBeans) { - try { - String beanName = determineBeanName(existingBeans, spyDefinition, registry); - registerSpy(spyDefinition, field, beanName); - } - catch (RuntimeException ex) { - throw new IllegalStateException("Unable to register spy bean " + spyDefinition.getTypeToSpy(), ex); - } - } - - private String determineBeanName(Collection existingBeans, SpyDefinition definition, - BeanDefinitionRegistry registry) { - if (StringUtils.hasText(definition.getName())) { - return definition.getName(); - } - if (existingBeans.size() == 1) { - return existingBeans.iterator().next(); - } - return determinePrimaryCandidate(registry, existingBeans, definition.getTypeToSpy()); - } - - private String determinePrimaryCandidate(BeanDefinitionRegistry registry, Collection candidateBeanNames, - ResolvableType type) { - String primaryBeanName = null; - for (String candidateBeanName : candidateBeanNames) { - BeanDefinition beanDefinition = registry.getBeanDefinition(candidateBeanName); - if (beanDefinition.isPrimary()) { - if (primaryBeanName != null) { - throw new NoUniqueBeanDefinitionException(type.resolve(), candidateBeanNames.size(), - "more than one 'primary' bean found among candidates: " - + Collections.singletonList(candidateBeanNames)); - } - primaryBeanName = candidateBeanName; - } - } - return primaryBeanName; - } - - private void registerSpy(SpyDefinition definition, Field field, String beanName) { - this.spies.put(beanName, definition); - this.beanNameRegistry.put(definition, beanName); - if (field != null) { - this.fieldRegistry.put(field, beanName); - } - } - - protected final Object createSpyIfNecessary(Object bean, String beanName) throws BeansException { - SpyDefinition definition = this.spies.get(beanName); - if (definition != null) { - bean = definition.createSpy(beanName, bean); - this.mockitoBeans.add(bean); - } - return bean; - } - - @Override - public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) - throws BeansException { - ReflectionUtils.doWithFields(bean.getClass(), (field) -> postProcessField(bean, field)); - return pvs; - } - - private void postProcessField(Object bean, Field field) { - String beanName = this.fieldRegistry.get(field); - if (StringUtils.hasText(beanName)) { - inject(field, bean, beanName); - } - } - - void inject(Field field, Object target, Definition definition) { - String beanName = this.beanNameRegistry.get(definition); - Assert.state(StringUtils.hasLength(beanName), () -> "No bean found for definition " + definition); - inject(field, target, beanName); - } - - private void inject(Field field, Object target, String beanName) { - try { - field.setAccessible(true); - Object existingValue = ReflectionUtils.getField(field, target); - Object bean = this.beanFactory.getBean(beanName, field.getType()); - if (existingValue == bean) { - return; - } - Assert.state(existingValue == null, () -> "The existing value '" + existingValue + "' of field '" + field - + "' is not the same as the new value '" + bean + "'"); - ReflectionUtils.setField(field, target, bean); - } - catch (Throwable ex) { - throw new BeanCreationException("Could not inject field: " + field, ex); - } - } - - @Override - public int getOrder() { - return Ordered.LOWEST_PRECEDENCE - 10; - } - - /** - * Register the processor with a {@link BeanDefinitionRegistry}. Not required when - * using the {@link SpringRunner} as registration is automatic. - * @param registry the bean definition registry - */ - public static void register(BeanDefinitionRegistry registry) { - register(registry, null); - } - - /** - * Register the processor with a {@link BeanDefinitionRegistry}. Not required when - * using the {@link SpringRunner} as registration is automatic. - * @param registry the bean definition registry - * @param definitions the initial mock/spy definitions - */ - public static void register(BeanDefinitionRegistry registry, Set definitions) { - register(registry, MockitoPostProcessor.class, definitions); - } - - /** - * Register the processor with a {@link BeanDefinitionRegistry}. Not required when - * using the {@link SpringRunner} as registration is automatic. - * @param registry the bean definition registry - * @param postProcessor the post processor class to register - * @param definitions the initial mock/spy definitions - */ - @SuppressWarnings("unchecked") - public static void register(BeanDefinitionRegistry registry, Class postProcessor, - Set definitions) { - SpyPostProcessor.register(registry); - BeanDefinition definition = getOrAddBeanDefinition(registry, postProcessor); - ValueHolder constructorArg = definition.getConstructorArgumentValues().getIndexedArgumentValue(0, Set.class); - Set existing = (Set) constructorArg.getValue(); - if (definitions != null) { - existing.addAll(definitions); - } - } - - private static BeanDefinition getOrAddBeanDefinition(BeanDefinitionRegistry registry, - Class postProcessor) { - if (!registry.containsBeanDefinition(BEAN_NAME)) { - RootBeanDefinition definition = new RootBeanDefinition(postProcessor); - definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, new LinkedHashSet<>()); - registry.registerBeanDefinition(BEAN_NAME, definition); - return definition; - } - return registry.getBeanDefinition(BEAN_NAME); - } - - /** - * {@link BeanPostProcessor} to handle {@link SpyBean} definitions. Registered as a - * separate processor so that it can be ordered above AOP post processors. - */ - static class SpyPostProcessor implements SmartInstantiationAwareBeanPostProcessor, PriorityOrdered { - - private static final String BEAN_NAME = SpyPostProcessor.class.getName(); - - private final Map earlySpyReferences = new ConcurrentHashMap<>(16); - - private final MockitoPostProcessor mockitoPostProcessor; - - SpyPostProcessor(MockitoPostProcessor mockitoPostProcessor) { - this.mockitoPostProcessor = mockitoPostProcessor; - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } - - @Override - public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { - if (bean instanceof FactoryBean) { - return bean; - } - this.earlySpyReferences.put(getCacheKey(bean, beanName), bean); - return this.mockitoPostProcessor.createSpyIfNecessary(bean, beanName); - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof FactoryBean) { - return bean; - } - if (this.earlySpyReferences.remove(getCacheKey(bean, beanName)) != bean) { - return this.mockitoPostProcessor.createSpyIfNecessary(bean, beanName); - } - return bean; - } - - private String getCacheKey(Object bean, String beanName) { - return StringUtils.hasLength(beanName) ? beanName : bean.getClass().getName(); - } - - static void register(BeanDefinitionRegistry registry) { - if (!registry.containsBeanDefinition(BEAN_NAME)) { - RootBeanDefinition definition = new RootBeanDefinition(SpyPostProcessor.class); - definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues(); - constructorArguments.addIndexedArgumentValue(0, - new RuntimeBeanReference(MockitoPostProcessor.BEAN_NAME)); - registry.registerBeanDefinition(BEAN_NAME, definition); - } - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java deleted file mode 100644 index e4d72905d1..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListener.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.BiConsumer; - -import org.mockito.Captor; -import org.mockito.MockitoAnnotations; - -import org.springframework.test.context.TestContext; -import org.springframework.test.context.TestExecutionListener; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; -import org.springframework.test.context.support.AbstractTestExecutionListener; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; - -/** - * {@link TestExecutionListener} to enable {@link MockBean @MockBean} and - * {@link SpyBean @SpyBean} support. Also triggers - * {@link MockitoAnnotations#openMocks(Object)} when any Mockito annotations used, - * primarily to allow {@link Captor @Captor} annotations. - *

- * To use the automatic reset support of {@code @MockBean} and {@code @SpyBean}, configure - * {@link ResetMocksTestExecutionListener} as well. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @author Moritz Halbritter - * @since 1.4.2 - * @see ResetMocksTestExecutionListener - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of Spring Framework's support for - * {@link MockitoBean} and {@link MockitoSpyBean}. - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class MockitoTestExecutionListener extends AbstractTestExecutionListener { - - private static final String MOCKS_ATTRIBUTE_NAME = MockitoTestExecutionListener.class.getName() + ".mocks"; - - @Override - public final int getOrder() { - return 1950; - } - - @Override - public void prepareTestInstance(TestContext testContext) throws Exception { - closeMocks(testContext); - initMocks(testContext); - injectFields(testContext); - } - - @Override - public void beforeTestMethod(TestContext testContext) throws Exception { - if (Boolean.TRUE.equals( - testContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) { - closeMocks(testContext); - initMocks(testContext); - reinjectFields(testContext); - } - } - - @Override - public void afterTestMethod(TestContext testContext) throws Exception { - closeMocks(testContext); - } - - @Override - public void afterTestClass(TestContext testContext) throws Exception { - closeMocks(testContext); - } - - private void initMocks(TestContext testContext) { - if (hasMockitoAnnotations(testContext)) { - testContext.setAttribute(MOCKS_ATTRIBUTE_NAME, MockitoAnnotations.openMocks(testContext.getTestInstance())); - } - } - - private void closeMocks(TestContext testContext) throws Exception { - Object mocks = testContext.getAttribute(MOCKS_ATTRIBUTE_NAME); - if (mocks instanceof AutoCloseable closeable) { - closeable.close(); - } - } - - private boolean hasMockitoAnnotations(TestContext testContext) { - MockitoAnnotationCollection collector = new MockitoAnnotationCollection(); - ReflectionUtils.doWithFields(testContext.getTestClass(), collector); - return collector.hasAnnotations(); - } - - private void injectFields(TestContext testContext) { - postProcessFields(testContext, (mockitoField, postProcessor) -> postProcessor.inject(mockitoField.field, - mockitoField.target, mockitoField.definition)); - } - - private void reinjectFields(final TestContext testContext) { - postProcessFields(testContext, (mockitoField, postProcessor) -> { - ReflectionUtils.makeAccessible(mockitoField.field); - ReflectionUtils.setField(mockitoField.field, testContext.getTestInstance(), null); - postProcessor.inject(mockitoField.field, mockitoField.target, mockitoField.definition); - }); - } - - private void postProcessFields(TestContext testContext, BiConsumer consumer) { - DefinitionsParser parser = new DefinitionsParser(); - parser.parse(testContext.getTestClass()); - if (!parser.getDefinitions().isEmpty()) { - MockitoPostProcessor postProcessor = testContext.getApplicationContext() - .getBean(MockitoPostProcessor.class); - for (Definition definition : parser.getDefinitions()) { - Field field = parser.getField(definition); - if (field != null) { - consumer.accept(new MockitoField(field, testContext.getTestInstance(), definition), postProcessor); - } - } - } - } - - /** - * {@link FieldCallback} to collect Mockito annotations. - */ - private static final class MockitoAnnotationCollection implements FieldCallback { - - private final Set annotations = new LinkedHashSet<>(); - - @Override - public void doWith(Field field) throws IllegalArgumentException { - for (Annotation annotation : field.getDeclaredAnnotations()) { - if (annotation.annotationType().getName().startsWith("org.mockito")) { - this.annotations.add(annotation); - } - } - } - - boolean hasAnnotations() { - return !this.annotations.isEmpty(); - } - - } - - private static final class MockitoField { - - private final Field field; - - private final Object target; - - private final Definition definition; - - private MockitoField(Field field, Object instance, Definition definition) { - this.field = field; - this.target = instance; - this.definition = definition; - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java deleted file mode 100644 index 3139311cb5..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/QualifierDefinition.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.Field; -import java.util.HashSet; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.config.DependencyDescriptor; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.core.annotation.MergedAnnotations; - -/** - * Definition of a Spring {@link Qualifier @Qualifier}. - * - * @author Phillip Webb - * @author Stephane Nicoll - * @see Definition - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class QualifierDefinition { - - private final Field field; - - private final DependencyDescriptor descriptor; - - private final Set annotations; - - QualifierDefinition(Field field, Set annotations) { - // We can't use the field or descriptor as part of the context key - // but we can assume that if two fields have the same qualifiers then - // it's safe for Spring to use either for qualifier logic - this.field = field; - this.descriptor = new DependencyDescriptor(field, true); - this.annotations = annotations; - } - - boolean matches(ConfigurableListableBeanFactory beanFactory, String beanName) { - return beanFactory.isAutowireCandidate(beanName, this.descriptor); - } - - void applyTo(RootBeanDefinition definition) { - definition.setQualifiedElement(this.field); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || !getClass().isAssignableFrom(obj.getClass())) { - return false; - } - QualifierDefinition other = (QualifierDefinition) obj; - return this.annotations.equals(other.annotations); - } - - @Override - public int hashCode() { - return this.annotations.hashCode(); - } - - static QualifierDefinition forElement(AnnotatedElement element) { - if (element instanceof Field field) { - Set annotations = getQualifierAnnotations(field); - if (!annotations.isEmpty()) { - return new QualifierDefinition(field, annotations); - } - } - return null; - } - - private static Set getQualifierAnnotations(Field field) { - // Assume that any annotations other than @MockBean/@SpyBean are qualifiers - Annotation[] candidates = field.getDeclaredAnnotations(); - Set annotations = new HashSet<>(candidates.length); - for (Annotation candidate : candidates) { - if (!isMockOrSpyAnnotation(candidate.annotationType())) { - annotations.add(candidate); - } - } - return annotations; - } - - private static boolean isMockOrSpyAnnotation(Class type) { - if (type.equals(MockBean.class) || type.equals(SpyBean.class)) { - return true; - } - MergedAnnotations metaAnnotations = MergedAnnotations.from(type); - return metaAnnotations.isPresent(MockBean.class) || metaAnnotations.isPresent(SpyBean.class); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java deleted file mode 100644 index 5c56997195..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListener.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import org.mockito.Mockito; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.NativeDetector; -import org.springframework.core.Ordered; -import org.springframework.test.context.TestContext; -import org.springframework.test.context.TestExecutionListener; -import org.springframework.test.context.support.AbstractTestExecutionListener; -import org.springframework.util.ClassUtils; - -/** - * {@link TestExecutionListener} to reset any mock beans that have been marked with a - * {@link MockReset}. Typically used alongside {@link MockitoTestExecutionListener}. - * - * @author Phillip Webb - * @since 1.4.0 - * @see MockitoTestExecutionListener - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link org.springframework.test.context.bean.override.mockito.MockitoResetTestExecutionListener} - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class ResetMocksTestExecutionListener extends AbstractTestExecutionListener { - - private static final boolean MOCKITO_IS_PRESENT = ClassUtils.isPresent("org.mockito.MockSettings", - ResetMocksTestExecutionListener.class.getClassLoader()); - - @Override - public int getOrder() { - return Ordered.LOWEST_PRECEDENCE - 100; - } - - @Override - public void beforeTestMethod(TestContext testContext) throws Exception { - if (MOCKITO_IS_PRESENT && !NativeDetector.inNativeImage()) { - resetMocks(testContext.getApplicationContext(), MockReset.BEFORE); - } - } - - @Override - public void afterTestMethod(TestContext testContext) throws Exception { - if (MOCKITO_IS_PRESENT && !NativeDetector.inNativeImage()) { - resetMocks(testContext.getApplicationContext(), MockReset.AFTER); - } - } - - private void resetMocks(ApplicationContext applicationContext, MockReset reset) { - if (applicationContext instanceof ConfigurableApplicationContext configurableContext) { - resetMocks(configurableContext, reset); - } - } - - private void resetMocks(ConfigurableApplicationContext applicationContext, MockReset reset) { - ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); - String[] names = beanFactory.getBeanDefinitionNames(); - Set instantiatedSingletons = new HashSet<>(Arrays.asList(beanFactory.getSingletonNames())); - for (String name : names) { - BeanDefinition definition = beanFactory.getBeanDefinition(name); - if (definition.isSingleton() && instantiatedSingletons.contains(name)) { - Object bean = getBean(beanFactory, name); - if (bean != null && reset.equals(MockReset.get(bean))) { - Mockito.reset(bean); - } - } - } - try { - MockitoBeans mockedBeans = beanFactory.getBean(MockitoBeans.class); - for (Object mockedBean : mockedBeans) { - if (reset.equals(MockReset.get(mockedBean))) { - Mockito.reset(mockedBean); - } - } - } - catch (NoSuchBeanDefinitionException ex) { - // Continue - } - if (applicationContext.getParent() != null) { - resetMocks(applicationContext.getParent(), reset); - } - } - - private Object getBean(ConfigurableListableBeanFactory beanFactory, String name) { - try { - if (isStandardBeanOrSingletonFactoryBean(beanFactory, name)) { - return beanFactory.getBean(name); - } - } - catch (Exception ex) { - // Continue - } - return beanFactory.getSingleton(name); - } - - private boolean isStandardBeanOrSingletonFactoryBean(ConfigurableListableBeanFactory beanFactory, String name) { - String factoryBeanName = BeanFactory.FACTORY_BEAN_PREFIX + name; - if (beanFactory.containsBean(factoryBeanName)) { - FactoryBean factoryBean = (FactoryBean) beanFactory.getBean(factoryBeanName); - return factoryBean.isSingleton(); - } - return true; - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpringBootMockResolver.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpringBootMockResolver.java deleted file mode 100644 index 43d0cca6b0..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpringBootMockResolver.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.mockito.plugins.MockResolver; - -import org.springframework.aop.TargetSource; -import org.springframework.aop.framework.Advised; -import org.springframework.aop.support.AopUtils; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; -import org.springframework.util.Assert; - -/** - * A {@link MockResolver} for testing Spring Boot applications with Mockito. It resolves - * mocks by walking the proxy chain until the target or a non-static proxy is found. - * - * @author Andy Wilkinson - * @since 2.4.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of Spring Framework's - * {@link MockitoBean} and {@link MockitoSpyBean} - */ -@Deprecated(since = "3.4.0", forRemoval = true) -public class SpringBootMockResolver implements MockResolver { - - @Override - public Object resolve(Object instance) { - return getUltimateTargetObject(instance); - } - - @SuppressWarnings("unchecked") - private static T getUltimateTargetObject(Object candidate) { - Assert.notNull(candidate, "'candidate' must not be null"); - try { - if (AopUtils.isAopProxy(candidate) && candidate instanceof Advised advised) { - TargetSource targetSource = advised.getTargetSource(); - if (targetSource.isStatic()) { - Object target = targetSource.getTarget(); - if (target != null) { - return getUltimateTargetObject(target); - } - } - } - } - catch (Throwable ex) { - throw new IllegalStateException("Failed to unwrap proxied object", ex); - } - return (T) candidate; - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyBean.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyBean.java deleted file mode 100644 index a5aaadc938..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyBean.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Repeatable; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.runner.RunWith; -import org.mockito.Mockito; - -import org.springframework.context.ApplicationContext; -import org.springframework.core.annotation.AliasFor; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * Annotation that can be used to apply Mockito spies to a Spring - * {@link ApplicationContext}. Can be used as a class level annotation or on fields in - * either {@code @Configuration} classes, or test classes that are - * {@link RunWith @RunWith} the {@link SpringRunner}. - *

- * Spies can be applied by type or by {@link #name() bean name}. All beans in the context - * of a matching type (including subclasses) will be wrapped with the spy. If no existing - * bean is defined a new one will be added. Dependencies that are known to the application - * context but are not beans (such as those - * {@link org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerResolvableDependency(Class, Object) - * registered directly}) will not be found and a spied bean will be added to the context - * alongside the existing dependency. - *

- * When {@code @SpyBean} is used on a field, as well as being registered in the - * application context, the spy will also be injected into the field. Typical usage might - * be:

- * @RunWith(SpringRunner.class)
- * public class ExampleTests {
- *
- *     @SpyBean
- *     private ExampleService service;
- *
- *     @Autowired
- *     private UserOfService userOfService;
- *
- *     @Test
- *     public void testUserOfService() {
- *         String actual = this.userOfService.makeUse();
- *         assertEquals("Was: Hello", actual);
- *         verify(this.service).greet();
- *     }
- *
- *     @Configuration
- *     @Import(UserOfService.class) // A @Component injected with ExampleService
- *     static class Config {
- *     }
- *
- *
- * }
- * 
If there is more than one bean of the requested type, qualifier metadata must be - * specified at field level:
- * @RunWith(SpringRunner.class)
- * public class ExampleTests {
- *
- *     @SpyBean
- *     @Qualifier("example")
- *     private ExampleService service;
- *
- *     ...
- * }
- * 
- *

- * This annotation is {@code @Repeatable} and may be specified multiple times when working - * with Java 8 or contained within a {@link SpyBeans @SpyBeans} annotation. - * - * @author Phillip Webb - * @since 1.4.0 - * @see MockitoPostProcessor - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link org.springframework.test.context.bean.override.mockito.MockitoSpyBean} - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@Target({ ElementType.TYPE, ElementType.FIELD }) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Repeatable(SpyBeans.class) -public @interface SpyBean { - - /** - * The name of the bean to spy. If not specified the name will either be generated or, - * if the spy is for an existing bean, the existing name will be used. - * @return the name of the bean - */ - String name() default ""; - - /** - * The classes to spy. This is an alias of {@link #classes()} which can be used for - * brevity if no other attributes are defined. See {@link #classes()} for details. - * @return the classes to spy - */ - @AliasFor("classes") - Class[] value() default {}; - - /** - * The classes to spy. Each class specified here will result in a spy being applied. - * Classes can be omitted when the annotation is used on a field. - *

- * When {@code @SpyBean} also defines a {@code name} this attribute can only contain a - * single value. - *

- * If this is the only specified attribute consider using the {@code value} alias - * instead. - * @return the classes to spy - */ - @AliasFor("value") - Class[] classes() default {}; - - /** - * The reset mode to apply to the spied bean. The default is {@link MockReset#AFTER} - * meaning that spies are automatically reset after each test method is invoked. - * @return the reset mode - */ - MockReset reset() default MockReset.AFTER; - - /** - * Indicates that Mockito methods such as {@link Mockito#verify(Object) verify(mock)} - * should use the {@code target} of AOP advised beans, rather than the proxy itself. - * If set to {@code false} you may need to use the result of - * {@link org.springframework.test.util.AopTestUtils#getUltimateTargetObject(Object) - * AopTestUtils.getUltimateTargetObject(...)} when calling Mockito methods. - * @return {@code true} if the target of AOP advised beans is used or {@code false} if - * the proxy is used directly - */ - boolean proxyTargetAware() default true; - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyBeans.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyBeans.java deleted file mode 100644 index 5e8cbdb37b..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyBeans.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Container annotation that aggregates several {@link SpyBean @SpyBean} annotations. - *

- * Can be used natively, declaring several nested {@link SpyBean @SpyBean} annotations. - * Can also be used in conjunction with Java 8's support for repeatable - * annotations, where {@link SpyBean @SpyBean} can simply be declared several times - * on the same {@linkplain ElementType#TYPE type}, implicitly generating this container - * annotation. - * - * @author Phillip Webb - * @since 1.4.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link org.springframework.test.context.bean.override.mockito.MockitoSpyBean} - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@Documented -public @interface SpyBeans { - - /** - * Return the contained {@link SpyBean @SpyBean} annotations. - * @return the spy beans - */ - SpyBean[] value(); - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java deleted file mode 100644 index 1c06075b31..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/SpyDefinition.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.reflect.Proxy; - -import org.mockito.AdditionalAnswers; -import org.mockito.MockSettings; -import org.mockito.Mockito; -import org.mockito.listeners.VerificationStartedEvent; -import org.mockito.listeners.VerificationStartedListener; - -import org.springframework.core.ResolvableType; -import org.springframework.core.style.ToStringCreator; -import org.springframework.test.util.AopTestUtils; -import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -import static org.mockito.Mockito.mock; - -/** - * A complete definition that can be used to create a Mockito spy. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class SpyDefinition extends Definition { - - private static final int MULTIPLIER = 31; - - private final ResolvableType typeToSpy; - - SpyDefinition(String name, ResolvableType typeToSpy, MockReset reset, boolean proxyTargetAware, - QualifierDefinition qualifier) { - super(name, reset, proxyTargetAware, qualifier); - Assert.notNull(typeToSpy, "'typeToSpy' must not be null"); - this.typeToSpy = typeToSpy; - - } - - ResolvableType getTypeToSpy() { - return this.typeToSpy; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || obj.getClass() != getClass()) { - return false; - } - SpyDefinition other = (SpyDefinition) obj; - boolean result = super.equals(obj); - result = result && ObjectUtils.nullSafeEquals(this.typeToSpy, other.typeToSpy); - return result; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = MULTIPLIER * result + ObjectUtils.nullSafeHashCode(this.typeToSpy); - return result; - } - - @Override - public String toString() { - return new ToStringCreator(this).append("name", getName()) - .append("typeToSpy", this.typeToSpy) - .append("reset", getReset()) - .toString(); - } - - T createSpy(Object instance) { - return createSpy(getName(), instance); - } - - @SuppressWarnings("unchecked") - T createSpy(String name, Object instance) { - Assert.notNull(instance, "'instance' must not be null"); - Assert.isInstanceOf(this.typeToSpy.resolve(), instance); - if (Mockito.mockingDetails(instance).isSpy()) { - return (T) instance; - } - MockSettings settings = MockReset.withSettings(getReset()); - if (StringUtils.hasLength(name)) { - settings.name(name); - } - if (isProxyTargetAware()) { - settings.verificationStartedListeners(new SpringAopBypassingVerificationStartedListener()); - } - Class toSpy; - if (Proxy.isProxyClass(instance.getClass())) { - settings.defaultAnswer(AdditionalAnswers.delegatesTo(instance)); - toSpy = this.typeToSpy.toClass(); - } - else { - settings.defaultAnswer(Mockito.CALLS_REAL_METHODS); - settings.spiedInstance(instance); - toSpy = instance.getClass(); - } - return (T) mock(toSpy, settings); - } - - /** - * A {@link VerificationStartedListener} that bypasses any proxy created by Spring AOP - * when the verification of a spy starts. - */ - private static final class SpringAopBypassingVerificationStartedListener implements VerificationStartedListener { - - @Override - public void onVerificationStarted(VerificationStartedEvent event) { - event.setMock(AopTestUtils.getUltimateTargetObject(event.getMock())); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/package-info.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/package-info.java deleted file mode 100644 index 21f0e1581d..0000000000 --- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Mockito integration for Spring Boot tests. - *

- * Deprecated since 3.4.0 for removal in 4.0.0 in favor of Spring Framework's - * {@link org.springframework.test.context.bean.override.mockito.MockitoBean} and - * {@link org.springframework.test.context.bean.override.mockito.MockitoSpyBean} - */ -package org.springframework.boot.test.mock.mockito; diff --git a/spring-boot-project/spring-boot-test/src/main/resources/META-INF/spring.factories b/spring-boot-project/spring-boot-test/src/main/resources/META-INF/spring.factories index 64bb8f6586..80760225f6 100644 --- a/spring-boot-project/spring-boot-test/src/main/resources/META-INF/spring.factories +++ b/spring-boot-project/spring-boot-test/src/main/resources/META-INF/spring.factories @@ -2,13 +2,7 @@ org.springframework.test.context.ContextCustomizerFactory=\ org.springframework.boot.test.context.ImportsContextCustomizerFactory,\ org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizerFactory,\ -org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory,\ -org.springframework.boot.test.mock.mockito.MockitoContextCustomizerFactory - -# Test Execution Listeners -org.springframework.test.context.TestExecutionListener=\ -org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener,\ -org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener +org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory # Application Context Initializers org.springframework.context.ApplicationContextInitializer=\ diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/AbstractMockBeanOnGenericExtensionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/AbstractMockBeanOnGenericExtensionTests.java deleted file mode 100644 index 87332b0146..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/AbstractMockBeanOnGenericExtensionTests.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -/** - * Concrete implementation of {@link AbstractMockBeanOnGenericTests}. - * - * @author Madhura Bhave - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class AbstractMockBeanOnGenericExtensionTests extends - AbstractMockBeanOnGenericTests { - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/AbstractMockBeanOnGenericTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/AbstractMockBeanOnGenericTests.java deleted file mode 100644 index 7122871819..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/AbstractMockBeanOnGenericTests.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link MockBean} with abstract class and generics. - * - * @param type of thing - * @param type of something - * @author Madhura Bhave - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@SpringBootTest(classes = AbstractMockBeanOnGenericTests.TestConfiguration.class) -abstract class AbstractMockBeanOnGenericTests, U extends AbstractMockBeanOnGenericTests.Something> { - - @Autowired - @SuppressWarnings("unused") - private T thing; - - @MockBean - private U something; - - @Test - void mockBeanShouldResolveConcreteType() { - assertThat(this.something).isInstanceOf(SomethingImpl.class); - } - - abstract static class Thing { - - @Autowired - private T something; - - T getSomething() { - return this.something; - } - - void setSomething(T something) { - this.something = something; - } - - } - - static class SomethingImpl extends Something { - - } - - static class ThingImpl extends Thing { - - } - - static class Something { - - } - - @Configuration - static class TestConfiguration { - - @Bean - ThingImpl thing() { - return new ThingImpl(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java deleted file mode 100644 index 2e56abc00f..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.mockito.Answers; - -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.mock.mockito.example.ExampleExtraInterface; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.RealExampleService; -import org.springframework.util.ReflectionUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; - -/** - * Tests for {@link DefinitionsParser}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class DefinitionsParserTests { - - private final DefinitionsParser parser = new DefinitionsParser(); - - @Test - void parseSingleMockBean() { - this.parser.parse(SingleMockBean.class); - assertThat(getDefinitions()).hasSize(1); - assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); - } - - @Test - void parseRepeatMockBean() { - this.parser.parse(RepeatMockBean.class); - assertThat(getDefinitions()).hasSize(2); - assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); - assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); - } - - @Test - void parseMockBeanAttributes() { - this.parser.parse(MockBeanAttributes.class); - assertThat(getDefinitions()).hasSize(1); - MockDefinition definition = getMockDefinition(0); - assertThat(definition.getName()).isEqualTo("Name"); - assertThat(definition.getTypeToMock().resolve()).isEqualTo(ExampleService.class); - assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class); - assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS); - assertThat(definition.isSerializable()).isTrue(); - assertThat(definition.getReset()).isEqualTo(MockReset.NONE); - assertThat(definition.getQualifier()).isNull(); - } - - @Test - void parseMockBeanOnClassAndField() { - this.parser.parse(MockBeanOnClassAndField.class); - assertThat(getDefinitions()).hasSize(2); - MockDefinition classDefinition = getMockDefinition(0); - assertThat(classDefinition.getTypeToMock().resolve()).isEqualTo(ExampleService.class); - assertThat(classDefinition.getQualifier()).isNull(); - MockDefinition fieldDefinition = getMockDefinition(1); - assertThat(fieldDefinition.getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); - QualifierDefinition qualifier = QualifierDefinition - .forElement(ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller")); - assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); - } - - @Test - void parseMockBeanInferClassToMock() { - this.parser.parse(MockBeanInferClassToMock.class); - assertThat(getDefinitions()).hasSize(1); - assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); - } - - @Test - void parseMockBeanMissingClassToMock() { - assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class)) - .withMessageContaining("Unable to deduce type to mock"); - } - - @Test - void parseMockBeanMultipleClasses() { - this.parser.parse(MockBeanMultipleClasses.class); - assertThat(getDefinitions()).hasSize(2); - assertThat(getMockDefinition(0).getTypeToMock().resolve()).isEqualTo(ExampleService.class); - assertThat(getMockDefinition(1).getTypeToMock().resolve()).isEqualTo(ExampleServiceCaller.class); - } - - @Test - void parseMockBeanMultipleClassesWithName() { - assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(MockBeanMultipleClassesWithName.class)) - .withMessageContaining("The name attribute can only be used when mocking a single class"); - } - - @Test - void parseSingleSpyBean() { - this.parser.parse(SingleSpyBean.class); - assertThat(getDefinitions()).hasSize(1); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); - } - - @Test - void parseRepeatSpyBean() { - this.parser.parse(RepeatSpyBean.class); - assertThat(getDefinitions()).hasSize(2); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); - assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); - } - - @Test - void parseSpyBeanAttributes() { - this.parser.parse(SpyBeanAttributes.class); - assertThat(getDefinitions()).hasSize(1); - SpyDefinition definition = getSpyDefinition(0); - assertThat(definition.getName()).isEqualTo("Name"); - assertThat(definition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); - assertThat(definition.getReset()).isEqualTo(MockReset.NONE); - assertThat(definition.getQualifier()).isNull(); - } - - @Test - void parseSpyBeanOnClassAndField() { - this.parser.parse(SpyBeanOnClassAndField.class); - assertThat(getDefinitions()).hasSize(2); - SpyDefinition classDefinition = getSpyDefinition(0); - assertThat(classDefinition.getQualifier()).isNull(); - assertThat(classDefinition.getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); - SpyDefinition fieldDefinition = getSpyDefinition(1); - QualifierDefinition qualifier = QualifierDefinition - .forElement(ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller")); - assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier); - assertThat(fieldDefinition.getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); - } - - @Test - void parseSpyBeanInferClassToMock() { - this.parser.parse(SpyBeanInferClassToMock.class); - assertThat(getDefinitions()).hasSize(1); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); - } - - @Test - void parseSpyBeanMissingClassToMock() { - assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class)) - .withMessageContaining("Unable to deduce type to spy"); - } - - @Test - void parseSpyBeanMultipleClasses() { - this.parser.parse(SpyBeanMultipleClasses.class); - assertThat(getDefinitions()).hasSize(2); - assertThat(getSpyDefinition(0).getTypeToSpy().resolve()).isEqualTo(RealExampleService.class); - assertThat(getSpyDefinition(1).getTypeToSpy().resolve()).isEqualTo(ExampleServiceCaller.class); - } - - @Test - void parseSpyBeanMultipleClassesWithName() { - assertThatIllegalStateException().isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class)) - .withMessageContaining("The name attribute can only be used when spying a single class"); - } - - private MockDefinition getMockDefinition(int index) { - return (MockDefinition) getDefinitions().get(index); - } - - private SpyDefinition getSpyDefinition(int index) { - return (SpyDefinition) getDefinitions().get(index); - } - - private List getDefinitions() { - return new ArrayList<>(this.parser.getDefinitions()); - } - - @SuppressWarnings("removal") - @MockBean(ExampleService.class) - static class SingleMockBean { - - } - - @SuppressWarnings("removal") - @MockBeans({ @MockBean(ExampleService.class), @MockBean(ExampleServiceCaller.class) }) - static class RepeatMockBean { - - } - - @SuppressWarnings("removal") - @MockBean(name = "Name", classes = ExampleService.class, extraInterfaces = ExampleExtraInterface.class, - answer = Answers.RETURNS_SMART_NULLS, serializable = true, reset = MockReset.NONE) - static class MockBeanAttributes { - - } - - @SuppressWarnings("removal") - @MockBean(ExampleService.class) - static class MockBeanOnClassAndField { - - @MockBean(ExampleServiceCaller.class) - @Qualifier("test") - private Object caller; - - } - - @SuppressWarnings("removal") - @MockBean({ ExampleService.class, ExampleServiceCaller.class }) - static class MockBeanMultipleClasses { - - } - - @SuppressWarnings("removal") - @MockBean(name = "name", classes = { ExampleService.class, ExampleServiceCaller.class }) - static class MockBeanMultipleClassesWithName { - - } - - static class MockBeanInferClassToMock { - - @MockBean - private ExampleService exampleService; - - } - - @SuppressWarnings("removal") - @MockBean - static class MockBeanMissingClassToMock { - - } - - @SuppressWarnings("removal") - @SpyBean(RealExampleService.class) - static class SingleSpyBean { - - } - - @SuppressWarnings("removal") - @SpyBeans({ @SpyBean(RealExampleService.class), @SpyBean(ExampleServiceCaller.class) }) - static class RepeatSpyBean { - - } - - @SuppressWarnings("removal") - @SpyBean(name = "Name", classes = RealExampleService.class, reset = MockReset.NONE) - static class SpyBeanAttributes { - - } - - @SuppressWarnings("removal") - @SpyBean(RealExampleService.class) - static class SpyBeanOnClassAndField { - - @SpyBean(ExampleServiceCaller.class) - @Qualifier("test") - private Object caller; - - } - - @SuppressWarnings("removal") - @SpyBean({ RealExampleService.class, ExampleServiceCaller.class }) - static class SpyBeanMultipleClasses { - - } - - @SuppressWarnings("removal") - @SpyBean(name = "name", classes = { RealExampleService.class, ExampleServiceCaller.class }) - static class SpyBeanMultipleClassesWithName { - - } - - static class SpyBeanInferClassToMock { - - @SpyBean - private RealExampleService exampleService; - - } - - @SuppressWarnings("removal") - @SpyBean - static class SpyBeanMissingClassToMock { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java deleted file mode 100644 index bde0d2fcd7..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanContextCachingTests.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Map; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTestContextBootstrapper; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.BootstrapContext; -import org.springframework.test.context.MergedContextConfiguration; -import org.springframework.test.context.TestContext; -import org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate; -import org.springframework.test.context.cache.DefaultContextCache; -import org.springframework.test.util.ReflectionTestUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * Tests for application context caching when using {@link MockBean @MockBean}. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockBeanContextCachingTests { - - private final DefaultContextCache contextCache = new DefaultContextCache(2); - - private final DefaultCacheAwareContextLoaderDelegate delegate = new DefaultCacheAwareContextLoaderDelegate( - this.contextCache); - - @AfterEach - @SuppressWarnings("unchecked") - void clearCache() { - Map contexts = (Map) ReflectionTestUtils - .getField(this.contextCache, "contextMap"); - for (ApplicationContext context : contexts.values()) { - if (context instanceof ConfigurableApplicationContext configurableContext) { - configurableContext.close(); - } - } - this.contextCache.clear(); - } - - @Test - void whenThereIsANormalBeanAndAMockBeanThenTwoContextsAreCreated() { - bootstrapContext(TestClass.class); - assertThat(this.contextCache.size()).isOne(); - bootstrapContext(MockedBeanTestClass.class); - assertThat(this.contextCache.size()).isEqualTo(2); - } - - @Test - void whenThereIsTheSameMockedBeanInEachTestClassThenOneContextIsCreated() { - bootstrapContext(MockedBeanTestClass.class); - assertThat(this.contextCache.size()).isOne(); - bootstrapContext(AnotherMockedBeanTestClass.class); - assertThat(this.contextCache.size()).isOne(); - } - - @SuppressWarnings("rawtypes") - private void bootstrapContext(Class testClass) { - SpringBootTestContextBootstrapper bootstrapper = new SpringBootTestContextBootstrapper(); - BootstrapContext bootstrapContext = mock(BootstrapContext.class); - given((Class) bootstrapContext.getTestClass()).willReturn(testClass); - bootstrapper.setBootstrapContext(bootstrapContext); - given(bootstrapContext.getCacheAwareContextLoaderDelegate()).willReturn(this.delegate); - TestContext testContext = bootstrapper.buildTestContext(); - testContext.getApplicationContext(); - } - - @SpringBootTest(classes = TestConfiguration.class) - static class TestClass { - - } - - @SpringBootTest(classes = TestConfiguration.class) - static class MockedBeanTestClass { - - @MockBean - private TestBean testBean; - - } - - @SpringBootTest(classes = TestConfiguration.class) - static class AnotherMockedBeanTestClass { - - @MockBean - private TestBean testBean; - - } - - @Configuration - static class TestConfiguration { - - @Bean - TestBean testBean() { - return new TestBean(); - } - - } - - static class TestBean { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java deleted file mode 100644 index ff9c648596..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanForBeanFactoryIntegrationTests.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * Test {@link MockBean @MockBean} for a factory bean. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanForBeanFactoryIntegrationTests { - - // gh-7439 - - @MockBean - private TestFactoryBean testFactoryBean; - - @Autowired - private ApplicationContext applicationContext; - - @Test - @SuppressWarnings({ "unchecked", "rawtypes" }) - void testName() { - TestBean testBean = mock(TestBean.class); - given(testBean.hello()).willReturn("amock"); - given(this.testFactoryBean.getObjectType()).willReturn((Class) TestBean.class); - given(this.testFactoryBean.getObject()).willReturn(testBean); - TestBean bean = this.applicationContext.getBean(TestBean.class); - assertThat(bean.hello()).isEqualTo("amock"); - } - - @Configuration(proxyBeanMethods = false) - static class Config { - - @Bean - TestFactoryBean testFactoryBean() { - return new TestFactoryBean(); - } - - } - - static class TestFactoryBean implements FactoryBean { - - @Override - public TestBean getObject() { - return () -> "normal"; - } - - @Override - public Class getObjectType() { - return TestBean.class; - } - - @Override - public boolean isSingleton() { - return false; - } - - } - - interface TestBean { - - String hello(); - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForExistingBeanIntegrationTests.java deleted file mode 100644 index b9d12d8bf1..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.FailingExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a configuration class can be used to replace - * existing beans. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanOnConfigurationClassForExistingBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.caller.getService().greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @SuppressWarnings("removal") - @Configuration(proxyBeanMethods = false) - @MockBean(ExampleService.class) - @Import({ ExampleServiceCaller.class, FailingExampleService.class }) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForNewBeanIntegrationTests.java deleted file mode 100644 index 1b7f964bf4..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationClassForNewBeanIntegrationTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a configuration class can be used to inject new mock - * instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@ExtendWith(SpringExtension.class) -@Deprecated(since = "3.4.0", forRemoval = true) -class MockBeanOnConfigurationClassForNewBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.caller.getService().greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @SuppressWarnings("removal") - @Configuration(proxyBeanMethods = false) - @MockBean(ExampleService.class) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForExistingBeanIntegrationTests.java deleted file mode 100644 index cbf05d98c9..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.FailingExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a field on a {@code @Configuration} class can be - * used to replace existing beans. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@ExtendWith(SpringExtension.class) -@Deprecated(since = "3.4.0", forRemoval = true) -class MockBeanOnConfigurationFieldForExistingBeanIntegrationTests { - - @Autowired - private Config config; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.config.exampleService.greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import({ ExampleServiceCaller.class, FailingExampleService.class }) - static class Config { - - @MockBean - private ExampleService exampleService; - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForNewBeanIntegrationTests.java deleted file mode 100644 index 553d8ebbe8..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnConfigurationFieldForNewBeanIntegrationTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a field on a {@code @Configuration} class can be - * used to inject new mock instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@ExtendWith(SpringExtension.class) -@Deprecated(since = "3.4.0", forRemoval = true) -class MockBeanOnConfigurationFieldForNewBeanIntegrationTests { - - @Autowired - private Config config; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.config.exampleService.greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - @MockBean - private ExampleService exampleService; - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java deleted file mode 100644 index 1827e0e25f..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnContextHierarchyIntegrationTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.ContextHierarchy; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test {@link MockBean @MockBean} can be used with a - * {@link ContextHierarchy @ContextHierarchy}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@ContextHierarchy({ @ContextConfiguration(classes = MockBeanOnContextHierarchyIntegrationTests.ParentConfig.class), - @ContextConfiguration(classes = MockBeanOnContextHierarchyIntegrationTests.ChildConfig.class) }) -class MockBeanOnContextHierarchyIntegrationTests { - - @Autowired - private ChildConfig childConfig; - - @Test - void testMocking() { - ApplicationContext context = this.childConfig.getContext(); - ApplicationContext parentContext = context.getParent(); - assertThat(parentContext - .getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleService.class)).hasSize(1); - assertThat(parentContext - .getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class)) - .isEmpty(); - assertThat(context.getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleService.class)) - .isEmpty(); - assertThat(context - .getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class)) - .hasSize(1); - assertThat(context.getBean(org.springframework.boot.test.mock.mockito.example.ExampleService.class)) - .isNotNull(); - assertThat(context.getBean(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class)) - .isNotNull(); - } - - @Configuration(proxyBeanMethods = false) - @MockBean(org.springframework.boot.test.mock.mockito.example.ExampleService.class) - static class ParentConfig { - - } - - @Configuration(proxyBeanMethods = false) - @MockBean(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class) - static class ChildConfig implements ApplicationContextAware { - - private ApplicationContext context; - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.context = applicationContext; - } - - ApplicationContext getContext() { - return this.context; - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnScopedProxyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnScopedProxyTests.java deleted file mode 100644 index fb294f8ca1..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnScopedProxyTests.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.FailingExampleService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Scope; -import org.springframework.context.annotation.ScopedProxyMode; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} when used in combination with scoped proxy targets. - * - * @author Phillip Webb - * @see gh-5724 - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanOnScopedProxyTests { - - @MockBean - private ExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.caller.getService().greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import({ ExampleServiceCaller.class }) - static class Config { - - @Bean - @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) - ExampleService exampleService() { - return new FailingExampleService(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForExistingBeanIntegrationTests.java deleted file mode 100644 index 0edce24e2c..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.FailingExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a test class can be used to replace existing beans. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@MockBean(ExampleService.class) -class MockBeanOnTestClassForExistingBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.caller.getService().greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import({ ExampleServiceCaller.class, FailingExampleService.class }) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForNewBeanIntegrationTests.java deleted file mode 100644 index f24c850c52..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestClassForNewBeanIntegrationTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a test class can be used to inject new mock - * instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@MockBean(ExampleService.class) -class MockBeanOnTestClassForNewBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.caller.getService().greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanCacheIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanCacheIntegrationTests.java deleted file mode 100644 index 78e12761a0..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanCacheIntegrationTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a test class field can be used to replace existing - * beans when the context is cached. This test is identical to - * {@link MockBeanOnTestFieldForExistingBeanIntegrationTests} so one of them should - * trigger application context caching. - * - * @author Phillip Webb - * @see MockBeanOnTestFieldForExistingBeanIntegrationTests - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = MockBeanOnTestFieldForExistingBeanConfig.class) -class MockBeanOnTestFieldForExistingBeanCacheIntegrationTests { - - @MockBean - private ExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.exampleService.greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanConfig.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanConfig.java deleted file mode 100644 index cbe41c94f0..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.FailingExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -/** - * Config for {@link MockBeanOnTestFieldForExistingBeanIntegrationTests} and - * {@link MockBeanOnTestFieldForExistingBeanCacheIntegrationTests}. Extracted to a shared - * config to trigger caching. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@Configuration(proxyBeanMethods = false) -@Import({ ExampleServiceCaller.class, FailingExampleService.class }) -public class MockBeanOnTestFieldForExistingBeanConfig { - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanIntegrationTests.java deleted file mode 100644 index 3e86bc87a1..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a test class field can be used to replace existing - * beans. - * - * @author Phillip Webb - * @see MockBeanOnTestFieldForExistingBeanCacheIntegrationTests - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = MockBeanOnTestFieldForExistingBeanConfig.class) -class MockBeanOnTestFieldForExistingBeanIntegrationTests { - - @MockBean - private ExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.exampleService.greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java deleted file mode 100644 index d105546e3e..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.CustomQualifier; -import org.springframework.boot.test.mock.mockito.example.CustomQualifierExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.RealExampleService; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link MockBean @MockBean} on a test class field can be used to replace existing - * bean while preserving qualifiers. - * - * @author Stephane Nicoll - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { - - @MockBean - @CustomQualifier - private ExampleService service; - - @Autowired - private ExampleServiceCaller caller; - - @Autowired - private ApplicationContext applicationContext; - - @Test - void testMocking() { - this.caller.sayGreeting(); - then(this.service).should().greeting(); - } - - @Test - void onlyQualifiedBeanIsReplaced() { - assertThat(this.applicationContext.getBean("service")).isSameAs(this.service); - ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class); - assertThat(anotherService.greeting()).isEqualTo("Another"); - } - - @Configuration(proxyBeanMethods = false) - static class TestConfig { - - @Bean - CustomQualifierExampleService service() { - return new CustomQualifierExampleService(); - } - - @Bean - ExampleService anotherService() { - return new RealExampleService("Another"); - } - - @Bean - ExampleServiceCaller controller(@CustomQualifier ExampleService service) { - return new ExampleServiceCaller(service); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForNewBeanIntegrationTests.java deleted file mode 100644 index a192da83c6..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanOnTestFieldForNewBeanIntegrationTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a test class field can be used to inject new mock - * instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanOnTestFieldForNewBeanIntegrationTests { - - @MockBean - private ExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.exampleService.greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAopProxyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAopProxyTests.java deleted file mode 100644 index de40e7d1c3..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAopProxyTests.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.cache.CacheManager; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.cache.concurrent.ConcurrentMapCacheManager; -import org.springframework.cache.interceptor.CacheResolver; -import org.springframework.cache.interceptor.SimpleCacheResolver; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.stereotype.Service; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.times; - -/** - * Test {@link MockBean @MockBean} when mixed with Spring AOP. - * - * @author Phillip Webb - * @see 5837 - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanWithAopProxyTests { - - @MockBean - private DateService dateService; - - @Test - void verifyShouldUseProxyTarget() { - given(this.dateService.getDate(false)).willReturn(1L); - Long d1 = this.dateService.getDate(false); - assertThat(d1).isOne(); - given(this.dateService.getDate(false)).willReturn(2L); - Long d2 = this.dateService.getDate(false); - assertThat(d2).isEqualTo(2L); - then(this.dateService).should(times(2)).getDate(false); - then(this.dateService).should(times(2)).getDate(eq(false)); - then(this.dateService).should(times(2)).getDate(anyBoolean()); - } - - @Configuration(proxyBeanMethods = false) - @EnableCaching(proxyTargetClass = true) - @Import(DateService.class) - static class Config { - - @Bean - CacheResolver cacheResolver(CacheManager cacheManager) { - SimpleCacheResolver resolver = new SimpleCacheResolver(); - resolver.setCacheManager(cacheManager); - return resolver; - } - - @Bean - ConcurrentMapCacheManager cacheManager() { - ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); - cacheManager.setCacheNames(Arrays.asList("test")); - return cacheManager; - } - - } - - @Service - static class DateService { - - @Cacheable(cacheNames = "test") - Long getDate(boolean argument) { - return System.nanoTime(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAsyncInterfaceMethodIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAsyncInterfaceMethodIntegrationTests.java deleted file mode 100644 index c12f8d1fb2..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithAsyncInterfaceMethodIntegrationTests.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.annotation.Async; -import org.springframework.scheduling.annotation.EnableAsync; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Tests for a mock bean where the mocked interface has an async method. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanWithAsyncInterfaceMethodIntegrationTests { - - @MockBean - private Transformer transformer; - - @Autowired - private MyService service; - - @Test - void mockedMethodsAreNotAsync() { - given(this.transformer.transform("foo")).willReturn("bar"); - assertThat(this.service.transform("foo")).isEqualTo("bar"); - } - - interface Transformer { - - @Async - String transform(String input); - - } - - static class MyService { - - private final Transformer transformer; - - MyService(Transformer transformer) { - this.transformer = transformer; - } - - String transform(String input) { - return this.transformer.transform(input); - } - - } - - @Configuration(proxyBeanMethods = false) - @EnableAsync - static class MyConfiguration { - - @Bean - MyService myService(Transformer transformer) { - return new MyService(transformer); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java deleted file mode 100644 index 6f3e47f760..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Integration tests for using {@link MockBean @MockBean} with - * {@link DirtiesContext @DirtiesContext} and {@link ClassMode#BEFORE_EACH_TEST_METHOD}. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) -class MockBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { - - @MockBean - private ExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testMocking() { - given(this.exampleService.greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests.java deleted file mode 100644 index f6e353c0e6..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleGenericService; -import org.springframework.boot.test.mock.mockito.example.ExampleGenericServiceCaller; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Test {@link MockBean @MockBean} on a test class field can be used to inject new mock - * instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanWithGenericsOnTestFieldForNewBeanIntegrationTests { - - @MockBean - private ExampleGenericService exampleIntegerService; - - @MockBean - private ExampleGenericService exampleStringService; - - @Autowired - private ExampleGenericServiceCaller caller; - - @Test - void testMocking() { - given(this.exampleIntegerService.greeting()).willReturn(200); - given(this.exampleStringService.greeting()).willReturn("Boot"); - assertThat(this.caller.sayGreeting()).isEqualTo("I say 200 Boot"); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleGenericServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithInjectedFieldIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithInjectedFieldIntegrationTests.java deleted file mode 100644 index 5c62dfe5a6..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithInjectedFieldIntegrationTests.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Tests for a mock bean where the class being mocked uses field injection. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockBeanWithInjectedFieldIntegrationTests { - - @MockBean - private MyService myService; - - @Test - void fieldInjectionIntoMyServiceMockIsNotAttempted() { - given(this.myService.getCount()).willReturn(5); - assertThat(this.myService.getCount()).isEqualTo(5); - } - - static class MyService { - - @Autowired - private MyRepository repository; - - int getCount() { - return this.repository.findAll().size(); - } - - } - - interface MyRepository { - - List findAll(); - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithSpringMethodRuleRepeatJUnit4IntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithSpringMethodRuleRepeatJUnit4IntegrationTests.java deleted file mode 100644 index 7fcff8fced..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockBeanWithSpringMethodRuleRepeatJUnit4IntegrationTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.AfterClass; -import org.junit.Rule; -import org.junit.Test; - -import org.springframework.test.annotation.Repeat; -import org.springframework.test.context.junit4.rules.SpringMethodRule; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link MockBean} and {@link Repeat}. - * - * @author Andy Wilkinson - * @see gh-27693 - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class MockBeanWithSpringMethodRuleRepeatJUnit4IntegrationTests { - - @Rule - public final SpringMethodRule springMethodRule = new SpringMethodRule(); - - @MockBean - private FirstService first; - - private static int invocations; - - @AfterClass - public static void afterClass() { - assertThat(invocations).isEqualTo(2); - } - - @Test - @Repeat(2) - public void repeatedTest() { - invocations++; - } - - interface FirstService { - - String greeting(); - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java deleted file mode 100644 index c34800b1ce..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.mockito.Answers; -import org.mockito.Mockito; -import org.mockito.mock.MockCreationSettings; - -import org.springframework.boot.test.mock.mockito.example.ExampleExtraInterface; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.core.ResolvableType; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; - -/** - * Tests for {@link MockDefinition}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockDefinitionTests { - - private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType.forClass(ExampleService.class); - - @Test - void classToMockMustNotBeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new MockDefinition(null, null, null, null, false, null, null)) - .withMessageContaining("'typeToMock' must not be null"); - } - - @Test - void createWithDefaults() { - MockDefinition definition = new MockDefinition(null, EXAMPLE_SERVICE_TYPE, null, null, false, null, null); - assertThat(definition.getName()).isNull(); - assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE); - assertThat(definition.getExtraInterfaces()).isEmpty(); - assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_DEFAULTS); - assertThat(definition.isSerializable()).isFalse(); - assertThat(definition.getReset()).isEqualTo(MockReset.AFTER); - assertThat(definition.getQualifier()).isNull(); - } - - @Test - void createExplicit() { - QualifierDefinition qualifier = mock(QualifierDefinition.class); - MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, - new Class[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, - qualifier); - assertThat(definition.getName()).isEqualTo("name"); - assertThat(definition.getTypeToMock()).isEqualTo(EXAMPLE_SERVICE_TYPE); - assertThat(definition.getExtraInterfaces()).containsExactly(ExampleExtraInterface.class); - assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS); - assertThat(definition.isSerializable()).isTrue(); - assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE); - assertThat(definition.isProxyTargetAware()).isFalse(); - assertThat(definition.getQualifier()).isEqualTo(qualifier); - } - - @Test - void createMock() { - MockDefinition definition = new MockDefinition("name", EXAMPLE_SERVICE_TYPE, - new Class[] { ExampleExtraInterface.class }, Answers.RETURNS_SMART_NULLS, true, MockReset.BEFORE, - null); - ExampleService mock = definition.createMock(); - MockCreationSettings settings = Mockito.mockingDetails(mock).getMockCreationSettings(); - assertThat(mock).isInstanceOf(ExampleService.class); - assertThat(mock).isInstanceOf(ExampleExtraInterface.class); - assertThat(settings.getMockName()).hasToString("name"); - assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS); - assertThat(settings.isSerializable()).isTrue(); - assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java deleted file mode 100644 index bc90e1fc3f..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockResetTests.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; - -import org.springframework.boot.test.mock.mockito.example.ExampleService; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.withSettings; - -/** - * Tests for {@link MockReset}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockResetTests { - - @Test - void noneAttachesReset() { - ExampleService mock = mock(ExampleService.class); - assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE); - } - - @Test - void withSettingsOfNoneAttachesReset() { - ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.NONE)); - assertThat(MockReset.get(mock)).isEqualTo(MockReset.NONE); - } - - @Test - void beforeAttachesReset() { - ExampleService mock = mock(ExampleService.class, MockReset.before()); - assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); - } - - @Test - void afterAttachesReset() { - ExampleService mock = mock(ExampleService.class, MockReset.after()); - assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER); - } - - @Test - void withSettingsAttachesReset() { - ExampleService mock = mock(ExampleService.class, MockReset.withSettings(MockReset.BEFORE)); - assertThat(MockReset.get(mock)).isEqualTo(MockReset.BEFORE); - } - - @Test - void apply() { - ExampleService mock = mock(ExampleService.class, MockReset.apply(MockReset.AFTER, withSettings())); - assertThat(MockReset.get(mock)).isEqualTo(MockReset.AFTER); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java deleted file mode 100644 index 260159ad69..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerFactoryTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; - -import org.springframework.test.context.ContextCustomizer; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link MockitoContextCustomizerFactory}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockitoContextCustomizerFactoryTests { - - private final MockitoContextCustomizerFactory factory = new MockitoContextCustomizerFactory(); - - @Test - void getContextCustomizerWithoutAnnotationReturnsCustomizer() { - ContextCustomizer customizer = this.factory.createContextCustomizer(NoMockBeanAnnotation.class, null); - assertThat(customizer).isNotNull(); - } - - @Test - void getContextCustomizerWithAnnotationReturnsCustomizer() { - ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); - assertThat(customizer).isNotNull(); - } - - @Test - void getContextCustomizerUsesMocksAsCacheKey() { - ContextCustomizer customizer = this.factory.createContextCustomizer(WithMockBeanAnnotation.class, null); - assertThat(customizer).isNotNull(); - ContextCustomizer same = this.factory.createContextCustomizer(WithSameMockBeanAnnotation.class, null); - assertThat(customizer).isNotNull(); - ContextCustomizer different = this.factory.createContextCustomizer(WithDifferentMockBeanAnnotation.class, null); - assertThat(different).isNotNull(); - assertThat(customizer).hasSameHashCodeAs(same); - assertThat(customizer.hashCode()).isNotEqualTo(different.hashCode()); - assertThat(customizer).isEqualTo(customizer).isEqualTo(same).isNotEqualTo(different); - } - - static class NoMockBeanAnnotation { - - } - - @SuppressWarnings("removal") - @MockBean({ Service1.class, Service2.class }) - static class WithMockBeanAnnotation { - - } - - @SuppressWarnings("removal") - @MockBean({ Service2.class, Service1.class }) - static class WithSameMockBeanAnnotation { - - } - - @SuppressWarnings("removal") - @MockBean({ Service1.class }) - static class WithDifferentMockBeanAnnotation { - - } - - interface Service1 { - - } - - interface Service2 { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java deleted file mode 100644 index 09003c94b2..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoContextCustomizerTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.junit.jupiter.api.Test; - -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.core.ResolvableType; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link MockitoContextCustomizer}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockitoContextCustomizerTests { - - private static final Set NO_DEFINITIONS = Collections.emptySet(); - - @Test - void hashCodeAndEquals() { - MockDefinition d1 = createTestMockDefinition(ExampleService.class); - MockDefinition d2 = createTestMockDefinition(ExampleServiceCaller.class); - MockitoContextCustomizer c1 = new MockitoContextCustomizer(NO_DEFINITIONS); - MockitoContextCustomizer c2 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d1, d2))); - MockitoContextCustomizer c3 = new MockitoContextCustomizer(new LinkedHashSet<>(Arrays.asList(d2, d1))); - assertThat(c2).hasSameHashCodeAs(c3); - assertThat(c1).isEqualTo(c1).isNotEqualTo(c2); - assertThat(c2).isEqualTo(c2).isEqualTo(c3).isNotEqualTo(c1); - } - - private MockDefinition createTestMockDefinition(Class typeToMock) { - return new MockDefinition(null, ResolvableType.forClass(typeToMock), null, null, false, null, null); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java deleted file mode 100644 index 50e814d428..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Map; - -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import org.springframework.beans.BeanWrapper; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.FailingExampleService; -import org.springframework.boot.test.mock.mockito.example.RealExampleService; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.core.Ordered; -import org.springframework.core.ResolvableType; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.util.Assert; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; - -/** - * Test for {@link MockitoPostProcessor}. See also the integration tests. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @author Andreas Neiser - * @author Madhura Bhave - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class MockitoPostProcessorTests { - - @Test - void cannotMockMultipleBeans() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - context.register(MultipleBeans.class); - assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace but found [example1, example2]"); - } - - @Test - void cannotMockMultipleQualifiedBeans() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - context.register(MultipleQualifiedBeans.class); - assertThatIllegalStateException().isThrownBy(context::refresh) - .withMessageContaining("Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace but found [example1, example3]"); - } - - @Test - void canMockBeanProducedByFactoryBeanWithClassObjectTypeAttribute() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(TestFactoryBean.class); - factoryBeanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, SomeInterface.class); - context.registerBeanDefinition("beanToBeMocked", factoryBeanDefinition); - context.register(MockedFactoryBean.class); - context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()).isTrue(); - } - - @Test - void canMockBeanProducedByFactoryBeanWithResolvableTypeObjectTypeAttribute() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - RootBeanDefinition factoryBeanDefinition = new RootBeanDefinition(TestFactoryBean.class); - ResolvableType objectType = ResolvableType.forClass(SomeInterface.class); - factoryBeanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, objectType); - context.registerBeanDefinition("beanToBeMocked", factoryBeanDefinition); - context.register(MockedFactoryBean.class); - context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean("beanToBeMocked")).isMock()).isTrue(); - } - - @Test - void canMockPrimaryBean() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - context.register(MockPrimaryBean.class); - context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean(MockPrimaryBean.class).mock).isMock()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()) - .isFalse(); - } - - @Test - void canMockQualifiedBeanWithPrimaryBeanPresent() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - context.register(MockQualifiedBean.class); - context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean(MockQualifiedBean.class).mock).isMock()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isMock()).isFalse(); - assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isMock()).isFalse(); - assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isMock()).isTrue(); - } - - @Test - void canSpyPrimaryBean() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - context.register(SpyPrimaryBean.class); - context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean(SpyPrimaryBean.class).spy).isSpy()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isFalse(); - } - - @Test - void canSpyQualifiedBeanWithPrimaryBeanPresent() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - MockitoPostProcessor.register(context); - context.register(SpyQualifiedBean.class); - context.refresh(); - assertThat(Mockito.mockingDetails(context.getBean(SpyQualifiedBean.class).spy).isSpy()).isTrue(); - assertThat(Mockito.mockingDetails(context.getBean(ExampleService.class)).isSpy()).isFalse(); - assertThat(Mockito.mockingDetails(context.getBean("examplePrimary", ExampleService.class)).isSpy()).isFalse(); - assertThat(Mockito.mockingDetails(context.getBean("exampleQualified", ExampleService.class)).isSpy()).isTrue(); - } - - @Test - void postProcessorShouldNotTriggerEarlyInitialization() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(FactoryBeanRegisteringPostProcessor.class); - MockitoPostProcessor.register(context); - context.register(TestBeanFactoryPostProcessor.class); - context.register(EagerInitBean.class); - context.refresh(); - } - - @Configuration(proxyBeanMethods = false) - @MockBean(SomeInterface.class) - static class MockedFactoryBean { - - @Bean - TestFactoryBean testFactoryBean() { - return new TestFactoryBean(); - } - - } - - @Configuration(proxyBeanMethods = false) - @MockBean(ExampleService.class) - static class MultipleBeans { - - @Bean - ExampleService example1() { - return new FailingExampleService(); - } - - @Bean - ExampleService example2() { - return new FailingExampleService(); - } - - } - - @Configuration(proxyBeanMethods = false) - static class MultipleQualifiedBeans { - - @MockBean - @Qualifier("test") - private ExampleService mock; - - @Bean - @Qualifier("test") - ExampleService example1() { - return new FailingExampleService(); - } - - @Bean - ExampleService example2() { - return new FailingExampleService(); - } - - @Bean - @Qualifier("test") - ExampleService example3() { - return new FailingExampleService(); - } - - } - - @Configuration(proxyBeanMethods = false) - static class MockPrimaryBean { - - @MockBean - private ExampleService mock; - - @Bean - @Qualifier("test") - ExampleService exampleQualified() { - return new RealExampleService("qualified"); - } - - @Bean - @Primary - ExampleService examplePrimary() { - return new RealExampleService("primary"); - } - - } - - @Configuration(proxyBeanMethods = false) - static class MockQualifiedBean { - - @MockBean - @Qualifier("test") - private ExampleService mock; - - @Bean - @Qualifier("test") - ExampleService exampleQualified() { - return new RealExampleService("qualified"); - } - - @Bean - @Primary - ExampleService examplePrimary() { - return new RealExampleService("primary"); - } - - } - - @Configuration(proxyBeanMethods = false) - static class SpyPrimaryBean { - - @SpyBean - private ExampleService spy; - - @Bean - @Qualifier("test") - ExampleService exampleQualified() { - return new RealExampleService("qualified"); - } - - @Bean - @Primary - ExampleService examplePrimary() { - return new RealExampleService("primary"); - } - - } - - @Configuration(proxyBeanMethods = false) - static class SpyQualifiedBean { - - @SpyBean - @Qualifier("test") - private ExampleService spy; - - @Bean - @Qualifier("test") - ExampleService exampleQualified() { - return new RealExampleService("qualified"); - } - - @Bean - @Primary - ExampleService examplePrimary() { - return new RealExampleService("primary"); - } - - } - - @Configuration(proxyBeanMethods = false) - static class EagerInitBean { - - @MockBean - private ExampleService service; - - } - - static class TestFactoryBean implements FactoryBean { - - @Override - public Object getObject() { - return new TestBean(); - } - - @Override - public Class getObjectType() { - return null; - } - - @Override - public boolean isSingleton() { - return true; - } - - } - - static class FactoryBeanRegisteringPostProcessor implements BeanFactoryPostProcessor, Ordered { - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - RootBeanDefinition beanDefinition = new RootBeanDefinition(TestFactoryBean.class); - ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition("test", beanDefinition); - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } - - } - - static class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { - - @Override - @SuppressWarnings("unchecked") - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - Map cache = (Map) ReflectionTestUtils.getField(beanFactory, - "factoryBeanInstanceCache"); - Assert.isTrue(cache.isEmpty(), "Early initialization of factory bean triggered."); - } - - } - - interface SomeInterface { - - } - - static class TestBean implements SomeInterface { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerIntegrationTests.java deleted file mode 100644 index eeba66c3ab..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerIntegrationTests.java +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.List; -import java.util.UUID; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.ClassOrderer; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestClassOrder; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestInstance.Lifecycle; -import org.junit.jupiter.api.TestMethodOrder; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.MockedStatic; - -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; - -/** - * Integration tests for {@link MockitoTestExecutionListener}. - * - * @author Moritz Halbritter - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class MockitoTestExecutionListenerIntegrationTests { - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - class MockedStaticTests { - - private static final UUID uuid = UUID.randomUUID(); - - @Mock - private MockedStatic mockedStatic; - - @Test - @Order(1) - @Disabled - void shouldReturnConstantValueDisabled() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - UUID result = UUID.randomUUID(); - assertThat(result).isEqualTo(uuid); - } - - @Test - @Order(2) - void shouldNotFailBecauseOfMockedStaticNotBeingClosed() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - UUID result = UUID.randomUUID(); - assertThat(result).isEqualTo(uuid); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) - class MockedStaticTestsDirtiesContext { - - private static final UUID uuid = UUID.randomUUID(); - - @Mock - private MockedStatic mockedStatic; - - @Test - @Order(1) - @Disabled - void shouldReturnConstantValueDisabled() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - UUID result = UUID.randomUUID(); - assertThat(result).isEqualTo(uuid); - } - - @Test - @Order(2) - void shouldNotFailBecauseOfMockedStaticNotBeingClosed() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - UUID result = UUID.randomUUID(); - assertThat(result).isEqualTo(uuid); - } - - @Test - @Order(3) - void shouldNotFailBecauseOfMockedStaticNotBeingClosedWhenMocksAreReinjected() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - UUID result = UUID.randomUUID(); - assertThat(result).isEqualTo(uuid); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @TestClassOrder(ClassOrderer.OrderAnnotation.class) - class MockedStaticTestsIfClassContainsOnlyDisabledTests { - - @Nested - @Order(1) - class TestClass1 { - - private static final UUID uuid = UUID.randomUUID(); - - @Mock - private MockedStatic mockedStatic; - - @Test - @Order(1) - @Disabled - void disabledTest() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - } - - } - - @Nested - @Order(2) - class TestClass2 { - - private static final UUID uuid = UUID.randomUUID(); - - @Mock - private MockedStatic mockedStatic; - - @Test - @Order(1) - void shouldNotFailBecauseMockedStaticHasNotBeenClosed() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - UUID result = UUID.randomUUID(); - assertThat(result).isEqualTo(uuid); - } - - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @TestClassOrder(ClassOrderer.OrderAnnotation.class) - class MockedStaticTestsIfClassContainsNoTests { - - @Nested - @Order(1) - class TestClass1 { - - @Mock - private MockedStatic mockedStatic; - - } - - @Nested - @Order(2) - class TestClass2 { - - private static final UUID uuid = UUID.randomUUID(); - - @Mock - private MockedStatic mockedStatic; - - @Test - @Order(1) - void shouldNotFailBecauseMockedStaticHasNotBeenClosed() { - this.mockedStatic.when(UUID::randomUUID).thenReturn(uuid); - UUID result = UUID.randomUUID(); - assertThat(result).isEqualTo(uuid); - } - - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - class ConfigureMockInBeforeEach { - - @Mock - private List mock; - - @BeforeEach - void setUp() { - given(this.mock.size()).willReturn(1); - } - - @Test - @Order(1) - void shouldUseSetUpConfiguration() { - assertThat(this.mock.size()).isEqualTo(1); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.size()).willReturn(2); - assertThat(this.mock.size()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldNotBeAffectedByOtherTests() { - assertThat(this.mock.size()).isEqualTo(1); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @TestInstance(Lifecycle.PER_CLASS) - @Disabled("https://github.com/spring-projects/spring-framework/issues/33690") - class ConfigureMockInBeforeAll { - - @Mock - private List mock; - - @BeforeAll - void setUp() { - given(this.mock.size()).willReturn(1); - } - - @Test - @Order(1) - void shouldUseSetUpConfiguration() { - assertThat(this.mock.size()).isEqualTo(1); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.size()).willReturn(2); - assertThat(this.mock.size()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldNotBeAffectedByOtherTest() { - assertThat(this.mock.size()).isEqualTo(2); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @Import(MyBeanConfiguration.class) - class ConfigureMockBeanWithResetAfterInBeforeEach { - - @MockBean(reset = MockReset.AFTER) - private MyBean mock; - - @BeforeEach - void setUp() { - given(this.mock.call()).willReturn(1); - } - - @Test - @Order(1) - void shouldUseSetUpConfiguration() { - assertThat(this.mock.call()).isEqualTo(1); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.call()).willReturn(2); - assertThat(this.mock.call()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldNotBeAffectedByOtherTests() { - assertThat(this.mock.call()).isEqualTo(1); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @Import(MyBeanConfiguration.class) - class ConfigureMockBeanWithResetBeforeInBeforeEach { - - @MockBean(reset = MockReset.BEFORE) - private MyBean mock; - - @BeforeEach - void setUp() { - given(this.mock.call()).willReturn(1); - } - - @Test - @Order(1) - void shouldUseSetUpConfiguration() { - assertThat(this.mock.call()).isEqualTo(1); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.call()).willReturn(2); - assertThat(this.mock.call()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldNotBeAffectedByOtherTests() { - assertThat(this.mock.call()).isEqualTo(1); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @Import(MyBeanConfiguration.class) - class ConfigureMockBeanWithResetNoneInBeforeEach { - - @MockBean(reset = MockReset.NONE) - private MyBean mock; - - @BeforeEach - void setUp() { - given(this.mock.call()).willReturn(1); - } - - @Test - @Order(1) - void shouldUseSetUpConfiguration() { - assertThat(this.mock.call()).isEqualTo(1); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.call()).willReturn(2); - assertThat(this.mock.call()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldNotBeAffectedByOtherTests() { - assertThat(this.mock.call()).isEqualTo(1); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @TestInstance(Lifecycle.PER_CLASS) - @Import(MyBeanConfiguration.class) - class ConfigureMockBeanWithResetAfterInBeforeAll { - - @MockBean(reset = MockReset.AFTER) - private MyBean mock; - - @BeforeAll - void setUp() { - given(this.mock.call()).willReturn(1); - } - - @Test - @Order(1) - void shouldUseSetUpConfiguration() { - assertThat(this.mock.call()).isEqualTo(1); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.call()).willReturn(2); - assertThat(this.mock.call()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldResetMockAfterReconfiguration() { - assertThat(this.mock.call()).isEqualTo(0); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @TestInstance(Lifecycle.PER_CLASS) - @Import(MyBeanConfiguration.class) - class ConfigureMockBeanWithResetBeforeInBeforeAll { - - @MockBean(reset = MockReset.BEFORE) - private MyBean mock; - - @BeforeAll - void setUp() { - given(this.mock.call()).willReturn(1); - } - - @Test - @Order(1) - void shouldResetMockBeforeThisMethod() { - assertThat(this.mock.call()).isEqualTo(0); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.call()).willReturn(2); - assertThat(this.mock.call()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldResetMockAfterReconfiguration() { - assertThat(this.mock.call()).isEqualTo(0); - } - - } - - @Nested - @TestMethodOrder(MethodOrderer.OrderAnnotation.class) - @TestInstance(Lifecycle.PER_CLASS) - @Import(MyBeanConfiguration.class) - class ConfigureMockBeanWithResetNoneInBeforeAll { - - @MockBean(reset = MockReset.NONE) - private MyBean mock; - - @BeforeAll - void setUp() { - given(this.mock.call()).willReturn(1); - } - - @Test - @Order(1) - void shouldUseSetUpConfiguration() { - assertThat(this.mock.call()).isEqualTo(1); - } - - @Test - @Order(2) - void shouldBeAbleToReconfigureMock() { - given(this.mock.call()).willReturn(2); - assertThat(this.mock.call()).isEqualTo(2); - } - - @Test - @Order(3) - void shouldNotResetMock() { - assertThat(this.mock.call()).isEqualTo(2); - } - - } - - interface MyBean { - - int call(); - - } - - private static final class DefaultMyBean implements MyBean { - - @Override - public int call() { - return -1; - } - - } - - @TestConfiguration(proxyBeanMethods = false) - private static final class MyBeanConfiguration { - - @Bean - MyBean myBean() { - return new DefaultMyBean(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java deleted file mode 100644 index fe4da63cf0..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoTestExecutionListenerTests.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.io.InputStream; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.TestContext; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.assertArg; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.mock; - -/** - * Tests for {@link MockitoTestExecutionListener}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(MockitoExtension.class) -class MockitoTestExecutionListenerTests { - - private final MockitoTestExecutionListener listener = new MockitoTestExecutionListener(); - - @Mock - private ApplicationContext applicationContext; - - @Mock - private MockitoPostProcessor postProcessor; - - @Test - void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception { - WithMockitoAnnotations instance = new WithMockitoAnnotations(); - this.listener.prepareTestInstance(mockTestContext(instance)); - assertThat(instance.mock).isNotNull(); - assertThat(instance.captor).isNotNull(); - } - - @Test - void prepareTestInstanceShouldInjectMockBean() throws Exception { - given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor); - WithMockBean instance = new WithMockBean(); - TestContext testContext = mockTestContext(instance); - given(testContext.getApplicationContext()).willReturn(this.applicationContext); - this.listener.prepareTestInstance(testContext); - then(this.postProcessor).should() - .inject(assertArg((field) -> assertThat(field.getName()).isEqualTo("mockBean")), eq(instance), - any(MockDefinition.class)); - } - - @Test - void beforeTestMethodShouldDoNothingWhenDirtiesContextAttributeIsNotSet() throws Exception { - this.listener.beforeTestMethod(mock(TestContext.class)); - then(this.postProcessor).shouldHaveNoMoreInteractions(); - } - - @Test - void beforeTestMethodShouldInjectMockBeanWhenDirtiesContextAttributeIsSet() throws Exception { - given(this.applicationContext.getBean(MockitoPostProcessor.class)).willReturn(this.postProcessor); - WithMockBean instance = new WithMockBean(); - TestContext mockTestContext = mockTestContext(instance); - given(mockTestContext.getApplicationContext()).willReturn(this.applicationContext); - given(mockTestContext.getAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE)) - .willReturn(Boolean.TRUE); - this.listener.beforeTestMethod(mockTestContext); - then(this.postProcessor).should() - .inject(assertArg((field) -> assertThat(field.getName()).isEqualTo("mockBean")), eq(instance), - any(MockDefinition.class)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private TestContext mockTestContext(Object instance) { - TestContext testContext = mock(TestContext.class); - given(testContext.getTestInstance()).willReturn(instance); - given(testContext.getTestClass()).willReturn((Class) instance.getClass()); - return testContext; - } - - static class WithMockitoAnnotations { - - @Mock - InputStream mock; - - @Captor - ArgumentCaptor captor; - - } - - static class WithMockBean { - - @MockBean - InputStream mockBean; - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java deleted file mode 100644 index 9f7cb1afc8..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/QualifierDefinitionTests.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.reflect.Field; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.ReflectionUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.assertArg; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.then; - -/** - * Tests for {@link QualifierDefinition}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(MockitoExtension.class) -class QualifierDefinitionTests { - - @Mock - private ConfigurableListableBeanFactory beanFactory; - - @Test - void forElementFieldIsNullShouldReturnNull() { - assertThat(QualifierDefinition.forElement((Field) null)).isNull(); - } - - @Test - void forElementWhenElementIsNotFieldShouldReturnNull() { - assertThat(QualifierDefinition.forElement(getClass())).isNull(); - } - - @Test - void forElementWhenElementIsFieldWithNoQualifiersShouldReturnNull() { - QualifierDefinition definition = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "noQualifier")); - assertThat(definition).isNull(); - } - - @Test - void forElementWhenElementIsFieldWithQualifierShouldReturnDefinition() { - QualifierDefinition definition = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); - assertThat(definition).isNotNull(); - } - - @Test - void matchesShouldCallBeanFactory() { - Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier"); - QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field); - qualifierDefinition.matches(this.beanFactory, "bean"); - then(this.beanFactory).should() - .isAutowireCandidate(eq("bean"), assertArg( - (dependencyDescriptor) -> assertThat(dependencyDescriptor.getAnnotatedElement()).isEqualTo(field))); - } - - @Test - void applyToShouldSetQualifierElement() { - Field field = ReflectionUtils.findField(ConfigA.class, "directQualifier"); - QualifierDefinition qualifierDefinition = QualifierDefinition.forElement(field); - RootBeanDefinition definition = new RootBeanDefinition(); - qualifierDefinition.applyTo(definition); - assertThat(definition.getQualifiedElement()).isEqualTo(field); - } - - @Test - void hashCodeAndEqualsShouldWorkOnDifferentClasses() { - QualifierDefinition directQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "directQualifier")); - QualifierDefinition directQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "directQualifier")); - QualifierDefinition differentDirectQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "differentDirectQualifier")); - QualifierDefinition differentDirectQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "differentDirectQualifier")); - QualifierDefinition customQualifier1 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigA.class, "customQualifier")); - QualifierDefinition customQualifier2 = QualifierDefinition - .forElement(ReflectionUtils.findField(ConfigB.class, "customQualifier")); - assertThat(directQualifier1).hasSameHashCodeAs(directQualifier2); - assertThat(differentDirectQualifier1).hasSameHashCodeAs(differentDirectQualifier2); - assertThat(customQualifier1).hasSameHashCodeAs(customQualifier2); - assertThat(differentDirectQualifier1).isEqualTo(differentDirectQualifier1) - .isEqualTo(differentDirectQualifier2) - .isNotEqualTo(directQualifier2); - assertThat(directQualifier1).isEqualTo(directQualifier1) - .isEqualTo(directQualifier2) - .isNotEqualTo(differentDirectQualifier1); - assertThat(customQualifier1).isEqualTo(customQualifier1) - .isEqualTo(customQualifier2) - .isNotEqualTo(differentDirectQualifier1); - } - - @Configuration(proxyBeanMethods = false) - static class ConfigA { - - @MockBean - private Object noQualifier; - - @MockBean - @Qualifier("test") - private Object directQualifier; - - @MockBean - @Qualifier("different") - private Object differentDirectQualifier; - - @MockBean - @CustomQualifier - private Object customQualifier; - - } - - static class ConfigB { - - @MockBean - @Qualifier("test") - private Object directQualifier; - - @MockBean - @Qualifier("different") - private Object differentDirectQualifier; - - @MockBean - @CustomQualifier - private Object customQualifier; - - } - - @Qualifier - @Retention(RetentionPolicy.RUNTIME) - public @interface CustomQualifier { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListenerTests.java deleted file mode 100644 index 7801392aa2..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/ResetMocksTestExecutionListenerTests.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Lazy; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * Tests for {@link ResetMocksTestExecutionListener}. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@TestMethodOrder(MethodOrderer.MethodName.class) -class ResetMocksTestExecutionListenerTests { - - @Autowired - private ApplicationContext context; - - @SpyBean - ToSpy spied; - - @Test - void test001() { - given(getMock("none").greeting()).willReturn("none"); - given(getMock("before").greeting()).willReturn("before"); - given(getMock("after").greeting()).willReturn("after"); - given(getMock("fromFactoryBean").greeting()).willReturn("fromFactoryBean"); - assertThat(this.context.getBean(NonSingletonFactoryBean.class).getObjectInvocations).isEqualTo(0); - given(this.spied.action()).willReturn("spied"); - } - - @Test - void test002() { - assertThat(getMock("none").greeting()).isEqualTo("none"); - assertThat(getMock("before").greeting()).isNull(); - assertThat(getMock("after").greeting()).isNull(); - assertThat(getMock("fromFactoryBean").greeting()).isNull(); - assertThat(this.context.getBean(NonSingletonFactoryBean.class).getObjectInvocations).isEqualTo(0); - assertThat(this.spied.action()).isNull(); - } - - ExampleService getMock(String name) { - return this.context.getBean(name, ExampleService.class); - } - - @Configuration(proxyBeanMethods = false) - static class Config { - - @Bean - ExampleService before(MockitoBeans mockedBeans) { - ExampleService mock = mock(ExampleService.class, MockReset.before()); - mockedBeans.add(mock); - return mock; - } - - @Bean - ExampleService after(MockitoBeans mockedBeans) { - ExampleService mock = mock(ExampleService.class, MockReset.after()); - mockedBeans.add(mock); - return mock; - } - - @Bean - ExampleService none(MockitoBeans mockedBeans) { - ExampleService mock = mock(ExampleService.class); - mockedBeans.add(mock); - return mock; - } - - @Bean - @Lazy - ExampleService fail() { - // gh-5870 - throw new RuntimeException(); - } - - @Bean - BrokenFactoryBean brokenFactoryBean() { - // gh-7270 - return new BrokenFactoryBean(); - } - - @Bean - WorkingFactoryBean fromFactoryBean() { - return new WorkingFactoryBean(); - } - - @Bean - NonSingletonFactoryBean nonSingletonFactoryBean() { - return new NonSingletonFactoryBean(); - } - - @Bean - ToSpyFactoryBean toSpyFactoryBean() { - return new ToSpyFactoryBean(); - } - - } - - static class BrokenFactoryBean implements FactoryBean { - - @Override - public String getObject() { - throw new IllegalStateException(); - } - - @Override - public Class getObjectType() { - return String.class; - } - - @Override - public boolean isSingleton() { - return true; - } - - } - - static class WorkingFactoryBean implements FactoryBean { - - private final ExampleService service = mock(ExampleService.class, MockReset.before()); - - @Override - public ExampleService getObject() { - return this.service; - } - - @Override - public Class getObjectType() { - return ExampleService.class; - } - - @Override - public boolean isSingleton() { - return true; - } - - } - - static class ToSpy { - - String action() { - return null; - } - - } - - static class NonSingletonFactoryBean implements FactoryBean { - - private int getObjectInvocations = 0; - - @Override - public ExampleService getObject() { - this.getObjectInvocations++; - return mock(ExampleService.class, MockReset.before()); - } - - @Override - public Class getObjectType() { - return ExampleService.class; - } - - @Override - public boolean isSingleton() { - return false; - } - - } - - static class ToSpyFactoryBean implements FactoryBean { - - @Override - public ToSpy getObject() throws Exception { - return new ToSpy(); - } - - @Override - public Class getObjectType() { - return ToSpy.class; - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpringBootMockResolverTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpringBootMockResolverTests.java deleted file mode 100644 index f28aa3ebf3..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpringBootMockResolverTests.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; - -import org.springframework.aop.SpringProxy; -import org.springframework.aop.framework.ProxyFactory; -import org.springframework.aop.target.HotSwappableTargetSource; -import org.springframework.aop.target.SingletonTargetSource; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link SpringBootMockResolver}. - * - * @author Moritz Halbritter - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class SpringBootMockResolverTests { - - @Test - void testStaticTarget() { - MyServiceImpl myService = new MyServiceImpl(); - MyService proxy = ProxyFactory.getProxy(MyService.class, new SingletonTargetSource(myService)); - Object target = new SpringBootMockResolver().resolve(proxy); - assertThat(target).isInstanceOf(MyServiceImpl.class); - } - - @Test - void testNonStaticTarget() { - MyServiceImpl myService = new MyServiceImpl(); - MyService proxy = ProxyFactory.getProxy(MyService.class, new HotSwappableTargetSource(myService)); - Object target = new SpringBootMockResolver().resolve(proxy); - assertThat(target).isInstanceOf(SpringProxy.class); - } - - private interface MyService { - - int a(); - - } - - private static final class MyServiceImpl implements MyService { - - @Override - public int a() { - return 1; - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForExistingBeanIntegrationTests.java deleted file mode 100644 index aa0e93ed84..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a configuration class can be used to spy existing - * beans. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnConfigurationClassForExistingBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.caller.getService()).should().greeting(); - } - - @SuppressWarnings("removal") - @Configuration(proxyBeanMethods = false) - @SpyBean(SimpleExampleService.class) - @Import({ ExampleServiceCaller.class, SimpleExampleService.class }) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForNewBeanIntegrationTests.java deleted file mode 100644 index 5a328b282f..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationClassForNewBeanIntegrationTests.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a configuration class can be used to inject new spy - * instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnConfigurationClassForNewBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.caller.getService()).should().greeting(); - } - - @SuppressWarnings("removal") - @Configuration(proxyBeanMethods = false) - @SpyBean(SimpleExampleService.class) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests.java deleted file mode 100644 index 293d418e0a..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a field on a {@code @Configuration} class can be used - * to replace existing beans. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnConfigurationFieldForExistingBeanIntegrationTests { - - @Autowired - private Config config; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.config.exampleService).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import({ ExampleServiceCaller.class, SimpleExampleService.class }) - static class Config { - - @SpyBean - private ExampleService exampleService; - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForNewBeanIntegrationTests.java deleted file mode 100644 index 23aca392eb..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnConfigurationFieldForNewBeanIntegrationTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a field on a {@code @Configuration} class can be used - * to inject new spy instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnConfigurationFieldForNewBeanIntegrationTests { - - @Autowired - private Config config; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.config.exampleService).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - @SpyBean - private SimpleExampleService exampleService; - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java deleted file mode 100644 index 38da81da1b..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnContextHierarchyIntegrationTests.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.ContextHierarchy; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test {@link SpyBean @SpyBean} can be used with a - * {@link ContextHierarchy @ContextHierarchy}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@ContextHierarchy({ @ContextConfiguration(classes = SpyBeanOnContextHierarchyIntegrationTests.ParentConfig.class), - @ContextConfiguration(classes = SpyBeanOnContextHierarchyIntegrationTests.ChildConfig.class) }) -class SpyBeanOnContextHierarchyIntegrationTests { - - @Autowired - private ChildConfig childConfig; - - @Test - void testSpying() { - ApplicationContext context = this.childConfig.getContext(); - ApplicationContext parentContext = context.getParent(); - assertThat(parentContext - .getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleService.class)).hasSize(1); - assertThat(parentContext - .getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class)) - .isEmpty(); - assertThat(context.getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleService.class)) - .isEmpty(); - assertThat(context - .getBeanNamesForType(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class)) - .hasSize(1); - assertThat(context.getBean(org.springframework.boot.test.mock.mockito.example.ExampleService.class)) - .isNotNull(); - assertThat(context.getBean(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class)) - .isNotNull(); - } - - @Configuration(proxyBeanMethods = false) - @SpyBean(org.springframework.boot.test.mock.mockito.example.SimpleExampleService.class) - static class ParentConfig { - - } - - @Configuration(proxyBeanMethods = false) - @SpyBean(org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller.class) - static class ChildConfig implements ApplicationContextAware { - - private ApplicationContext context; - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.context = applicationContext; - } - - ApplicationContext getContext() { - return this.context; - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForExistingBeanIntegrationTests.java deleted file mode 100644 index ee008a5509..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class can be used to replace existing beans. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@SpyBean(SimpleExampleService.class) -class SpyBeanOnTestClassForExistingBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.caller.getService()).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import({ ExampleServiceCaller.class, SimpleExampleService.class }) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForNewBeanIntegrationTests.java deleted file mode 100644 index ba1c9ce013..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestClassForNewBeanIntegrationTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class can be used to inject new spy instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@SpyBean(SimpleExampleService.class) -class SpyBeanOnTestClassForNewBeanIntegrationTests { - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.caller.getService()).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests.java deleted file mode 100644 index 44eb0c543f..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to replace existing - * beans when the context is cached. This test is identical to - * {@link SpyBeanOnTestFieldForExistingBeanIntegrationTests} so one of them should trigger - * application context caching. - * - * @author Phillip Webb - * @see SpyBeanOnTestFieldForExistingBeanIntegrationTests - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = SpyBeanOnTestFieldForExistingBeanConfig.class) -class SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests { - - @SpyBean - private ExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.caller.getService()).should().greeting(); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanConfig.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanConfig.java deleted file mode 100644 index 469d0c2c4f..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -/** - * Config for {@link SpyBeanOnTestFieldForExistingBeanIntegrationTests} and - * {@link SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests}. Extracted to a shared - * config to trigger caching. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@Configuration(proxyBeanMethods = false) -@Import({ ExampleServiceCaller.class, SimpleExampleService.class }) -public class SpyBeanOnTestFieldForExistingBeanConfig { - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanIntegrationTests.java deleted file mode 100644 index 0645169c62..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanIntegrationTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to replace existing - * beans. - * - * @author Phillip Webb - * @see SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = SpyBeanOnTestFieldForExistingBeanConfig.class) -class SpyBeanOnTestFieldForExistingBeanIntegrationTests { - - @SpyBean - private ExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.caller.getService()).should().greeting(); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java deleted file mode 100644 index 1f2b27c561..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.CustomQualifier; -import org.springframework.boot.test.mock.mockito.example.CustomQualifierExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.RealExampleService; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to replace existing - * bean while preserving qualifiers. - * - * @author Andreas Neiser - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnTestFieldForExistingBeanWithQualifierIntegrationTests { - - @SpyBean - @CustomQualifier - private ExampleService service; - - @Autowired - private ExampleServiceCaller caller; - - @Autowired - private ApplicationContext applicationContext; - - @Test - void testMocking() { - this.caller.sayGreeting(); - then(this.service).should().greeting(); - } - - @Test - void onlyQualifiedBeanIsReplaced() { - assertThat(this.applicationContext.getBean("service")).isSameAs(this.service); - ExampleService anotherService = this.applicationContext.getBean("anotherService", ExampleService.class); - assertThat(anotherService.greeting()).isEqualTo("Another"); - } - - @Configuration(proxyBeanMethods = false) - static class TestConfig { - - @Bean - CustomQualifierExampleService service() { - return new CustomQualifierExampleService(); - } - - @Bean - ExampleService anotherService() { - return new RealExampleService("Another"); - } - - @Bean - ExampleServiceCaller controller(@CustomQualifier ExampleService service) { - return new ExampleServiceCaller(service); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingCircularBeansIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingCircularBeansIntegrationTests.java deleted file mode 100644 index f6437a67e3..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingCircularBeansIntegrationTests.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to replace existing - * beans with circular dependencies. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@ContextConfiguration( - classes = SpyBeanOnTestFieldForExistingCircularBeansIntegrationTests.SpyBeanOnTestFieldForExistingCircularBeansConfig.class) -class SpyBeanOnTestFieldForExistingCircularBeansIntegrationTests { - - @SpyBean - private One one; - - @Autowired - private Two two; - - @Test - void beanWithCircularDependenciesCanBeSpied() { - this.two.callOne(); - then(this.one).should().someMethod(); - } - - @Import({ One.class, Two.class }) - static class SpyBeanOnTestFieldForExistingCircularBeansConfig { - - } - - static class One { - - @Autowired - @SuppressWarnings("unused") - private Two two; - - void someMethod() { - - } - - } - - static class Two { - - @Autowired - private One one; - - void callOne() { - this.one.someMethod(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java deleted file mode 100644 index b8dfc4ee22..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleGenericService; -import org.springframework.boot.test.mock.mockito.example.ExampleGenericServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleIntegerGenericService; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleStringGenericService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to replace existing - * beans. - * - * @author Phillip Webb - * @see SpyBeanOnTestFieldForExistingBeanCacheIntegrationTests - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnTestFieldForExistingGenericBeanIntegrationTests { - - // gh-7625 - - @SpyBean - private ExampleGenericService exampleService; - - @Autowired - private ExampleGenericServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say 123 simple"); - then(this.exampleService).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import({ ExampleGenericServiceCaller.class, SimpleExampleIntegerGenericService.class }) - static class SpyBeanOnTestFieldForExistingBeanConfig { - - @Bean - ExampleGenericService simpleExampleStringGenericService() { - // In order to trigger issue we need a method signature that returns the - // generic type not the actual implementation class - return new SimpleExampleStringGenericService(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanProducedByFactoryBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanProducedByFactoryBeanIntegrationTests.java deleted file mode 100644 index 5711ba771c..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForExistingGenericBeanProducedByFactoryBeanIntegrationTests.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.boot.test.mock.mockito.example.ExampleGenericService; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleStringGenericService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.ResolvableType; -import org.springframework.core.type.AnnotationMetadata; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to replace an existing - * bean with generics that's produced by a factory bean. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnTestFieldForExistingGenericBeanProducedByFactoryBeanIntegrationTests { - - // gh-40234 - - @SpyBean(name = "exampleService") - private ExampleGenericService exampleService; - - @Test - void testSpying() { - assertThat(Mockito.mockingDetails(this.exampleService).isSpy()).isTrue(); - assertThat(Mockito.mockingDetails(this.exampleService).getMockCreationSettings().getSpiedInstance()) - .isInstanceOf(SimpleExampleStringGenericService.class); - } - - @Configuration(proxyBeanMethods = false) - @Import(FactoryBeanRegistrar.class) - static class SpyBeanOnTestFieldForExistingBeanConfig { - - } - - static class FactoryBeanRegistrar implements ImportBeanDefinitionRegistrar { - - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { - RootBeanDefinition definition = new RootBeanDefinition(ExampleGenericServiceFactoryBean.class); - definition.setTargetType(ResolvableType.forClassWithGenerics(ExampleGenericServiceFactoryBean.class, null, - ExampleGenericService.class)); - registry.registerBeanDefinition("exampleService", definition); - } - - } - - static class ExampleGenericServiceFactoryBean> implements FactoryBean { - - @SuppressWarnings("unchecked") - @Override - public U getObject() throws Exception { - return (U) new SimpleExampleStringGenericService(); - } - - @Override - @SuppressWarnings("rawtypes") - public Class getObjectType() { - return ExampleGenericService.class; - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java deleted file mode 100644 index 073c2c78c1..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleGenericStringServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleStringGenericService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Primary; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to inject a spy - * instance when there are multiple candidates and one is primary. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnTestFieldForMultipleExistingBeansWithOnePrimaryIntegrationTests { - - @SpyBean - private SimpleExampleStringGenericService spy; - - @Autowired - private ExampleGenericStringServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say two"); - assertThat(Mockito.mockingDetails(this.spy).getMockCreationSettings().getMockName()).hasToString("two"); - then(this.spy).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleGenericStringServiceCaller.class) - static class Config { - - @Bean - SimpleExampleStringGenericService one() { - return new SimpleExampleStringGenericService("one"); - } - - @Bean - @Primary - SimpleExampleStringGenericService two() { - return new SimpleExampleStringGenericService("two"); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForNewBeanIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForNewBeanIntegrationTests.java deleted file mode 100644 index 3a2e5c29da..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanOnTestFieldForNewBeanIntegrationTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to inject new spy - * instances. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanOnTestFieldForNewBeanIntegrationTests { - - @SpyBean - private SimpleExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - assertThat(this.caller.sayGreeting()).isEqualTo("I say simple"); - then(this.caller.getService()).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java deleted file mode 100644 index 4b9cf9dd69..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyAndNotProxyTargetAwareTests.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.exceptions.misusing.UnfinishedVerificationException; - -import org.springframework.cache.CacheManager; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.cache.concurrent.ConcurrentMapCacheManager; -import org.springframework.cache.interceptor.CacheResolver; -import org.springframework.cache.interceptor.SimpleCacheResolver; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.stereotype.Service; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.reset; - -/** - * Test {@link SpyBean @SpyBean} when mixed with Spring AOP. - * - * @author Phillip Webb - * @see 5837 - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanWithAopProxyAndNotProxyTargetAwareTests { - - @SpyBean(proxyTargetAware = false) - private DateService dateService; - - @Test - void verifyShouldUseProxyTarget() { - this.dateService.getDate(false); - then(this.dateService).should().getDate(false); - assertThatExceptionOfType(UnfinishedVerificationException.class).isThrownBy(() -> reset(this.dateService)); - } - - @Configuration(proxyBeanMethods = false) - @EnableCaching(proxyTargetClass = true) - @Import(DateService.class) - static class Config { - - @Bean - CacheResolver cacheResolver(CacheManager cacheManager) { - SimpleCacheResolver resolver = new SimpleCacheResolver(); - resolver.setCacheManager(cacheManager); - return resolver; - } - - @Bean - ConcurrentMapCacheManager cacheManager() { - ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); - cacheManager.setCacheNames(Arrays.asList("test")); - return cacheManager; - } - - } - - @Service - public static class DateService { - - @Cacheable(cacheNames = "test") - public Long getDate(boolean arg) { - return System.nanoTime(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyTests.java deleted file mode 100644 index 402afcb65e..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithAopProxyTests.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.util.Arrays; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.cache.CacheManager; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.cache.annotation.EnableCaching; -import org.springframework.cache.concurrent.ConcurrentMapCacheManager; -import org.springframework.cache.interceptor.CacheResolver; -import org.springframework.cache.interceptor.SimpleCacheResolver; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.stereotype.Service; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.then; - -/** - * Test {@link SpyBean @SpyBean} when mixed with Spring AOP. - * - * @author Phillip Webb - * @see 5837 - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanWithAopProxyTests { - - @SpyBean - private DateService dateService; - - @Test - void verifyShouldUseProxyTarget() throws Exception { - Long d1 = this.dateService.getDate(false); - Thread.sleep(200); - Long d2 = this.dateService.getDate(false); - assertThat(d1).isEqualTo(d2); - then(this.dateService).should().getDate(false); - then(this.dateService).should().getDate(eq(false)); - then(this.dateService).should().getDate(anyBoolean()); - } - - @Configuration(proxyBeanMethods = false) - @EnableCaching(proxyTargetClass = true) - @Import(DateService.class) - static class Config { - - @Bean - CacheResolver cacheResolver(CacheManager cacheManager) { - SimpleCacheResolver resolver = new SimpleCacheResolver(); - resolver.setCacheManager(cacheManager); - return resolver; - } - - @Bean - ConcurrentMapCacheManager cacheManager() { - ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(); - cacheManager.setCacheNames(Arrays.asList("test")); - return cacheManager; - } - - } - - @Service - public static class DateService { - - @Cacheable(cacheNames = "test") - public Long getDate(boolean arg) { - return System.nanoTime(); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java deleted file mode 100644 index c270a612d0..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.SimpleExampleService; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.mockito.BDDMockito.then; - -/** - * Integration tests for using {@link SpyBean @SpyBean} with - * {@link DirtiesContext @DirtiesContext} and {@link ClassMode#BEFORE_EACH_TEST_METHOD}. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) -class SpyBeanWithDirtiesContextClassModeBeforeMethodIntegrationTests { - - @SpyBean - private SimpleExampleService exampleService; - - @Autowired - private ExampleServiceCaller caller; - - @Test - void testSpying() { - this.caller.sayGreeting(); - then(this.exampleService).should().greeting(); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleServiceCaller.class) - static class Config { - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithJdkProxyTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithJdkProxyTests.java deleted file mode 100644 index ae8e2debaa..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithJdkProxyTests.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import java.lang.reflect.Proxy; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Tests for {@link SpyBean @SpyBean} with a JDK proxy. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanWithJdkProxyTests { - - @Autowired - private ExampleService service; - - @SpyBean - private ExampleRepository repository; - - @Test - void jdkProxyCanBeSpied() { - Example example = this.service.find("id"); - assertThat(example.id).isEqualTo("id"); - then(this.repository).should().find("id"); - } - - @Configuration(proxyBeanMethods = false) - @Import(ExampleService.class) - static class Config { - - @Bean - ExampleRepository dateService() { - return (ExampleRepository) Proxy.newProxyInstance(getClass().getClassLoader(), - new Class[] { ExampleRepository.class }, (proxy, method, args) -> new Example((String) args[0])); - } - - } - - static class ExampleService { - - private final ExampleRepository repository; - - ExampleService(ExampleRepository repository) { - this.repository = repository; - } - - Example find(String id) { - return this.repository.find(id); - } - - } - - interface ExampleRepository { - - Example find(String id); - - } - - static class Example { - - private final String id; - - Example(String id) { - this.id = id; - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java deleted file mode 100644 index c8251df5d0..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.MockingDetails; -import org.mockito.Mockito; - -import org.springframework.boot.test.mock.mockito.example.SimpleExampleStringGenericService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Test {@link SpyBean @SpyBean} on a test class field can be used to inject a spy - * instance when there are multiple candidates and one is chosen using the name attribute. - * - * @author Phillip Webb - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@ExtendWith(SpringExtension.class) -class SpyBeanWithNameOnTestFieldForMultipleExistingBeansTests { - - @SpyBean(name = "two") - private SimpleExampleStringGenericService spy; - - @Test - void testSpying() { - MockingDetails mockingDetails = Mockito.mockingDetails(this.spy); - assertThat(mockingDetails.isSpy()).isTrue(); - assertThat(mockingDetails.getMockCreationSettings().getMockName()).hasToString("two"); - } - - @Configuration(proxyBeanMethods = false) - static class Config { - - @Bean - SimpleExampleStringGenericService one() { - return new SimpleExampleStringGenericService("one"); - } - - @Bean - SimpleExampleStringGenericService two() { - return new SimpleExampleStringGenericService("two"); - } - - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java deleted file mode 100644 index f7416309e3..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito; - -import org.junit.jupiter.api.Test; -import org.mockito.Answers; -import org.mockito.Mockito; -import org.mockito.mock.MockCreationSettings; - -import org.springframework.boot.test.mock.mockito.example.ExampleService; -import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller; -import org.springframework.boot.test.mock.mockito.example.RealExampleService; -import org.springframework.core.ResolvableType; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.Mockito.mock; - -/** - * Tests for {@link SpyDefinition}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class SpyDefinitionTests { - - private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType.forClass(RealExampleService.class); - - @Test - void classToSpyMustNotBeNull() { - assertThatIllegalArgumentException().isThrownBy(() -> new SpyDefinition(null, null, null, true, null)) - .withMessageContaining("'typeToSpy' must not be null"); - } - - @Test - void createWithDefaults() { - SpyDefinition definition = new SpyDefinition(null, REAL_SERVICE_TYPE, null, true, null); - assertThat(definition.getName()).isNull(); - assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE); - assertThat(definition.getReset()).isEqualTo(MockReset.AFTER); - assertThat(definition.isProxyTargetAware()).isTrue(); - assertThat(definition.getQualifier()).isNull(); - } - - @Test - void createExplicit() { - QualifierDefinition qualifier = mock(QualifierDefinition.class); - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, false, qualifier); - assertThat(definition.getName()).isEqualTo("name"); - assertThat(definition.getTypeToSpy()).isEqualTo(REAL_SERVICE_TYPE); - assertThat(definition.getReset()).isEqualTo(MockReset.BEFORE); - assertThat(definition.isProxyTargetAware()).isFalse(); - assertThat(definition.getQualifier()).isEqualTo(qualifier); - } - - @Test - void createSpy() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); - RealExampleService spy = definition.createSpy(new RealExampleService("hello")); - MockCreationSettings settings = Mockito.mockingDetails(spy).getMockCreationSettings(); - assertThat(spy).isInstanceOf(ExampleService.class); - assertThat(settings.getMockName()).hasToString("name"); - assertThat(settings.getDefaultAnswer()).isEqualTo(Answers.CALLS_REAL_METHODS); - assertThat(MockReset.get(spy)).isEqualTo(MockReset.BEFORE); - } - - @Test - void createSpyWhenNullInstanceShouldThrowException() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); - assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(null)) - .withMessageContaining("'instance' must not be null"); - } - - @Test - void createSpyWhenWrongInstanceShouldThrowException() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); - assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null))) - .withMessageContaining("must be an instance of"); - } - - @Test - void createSpyTwice() { - SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); - Object instance = new RealExampleService("hello"); - instance = definition.createSpy(instance); - definition.createSpy(instance); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/CustomQualifier.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/CustomQualifier.java deleted file mode 100644 index 7c9a4f0fa4..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/CustomQualifier.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import org.springframework.beans.factory.annotation.Qualifier; - -/** - * Custom qualifier for testing. - * - * @author Stephane Nicoll - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@Deprecated(since = "3.4.0", forRemoval = true) -@Qualifier -@Retention(RetentionPolicy.RUNTIME) -public @interface CustomQualifier { - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/CustomQualifierExampleService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/CustomQualifierExampleService.java deleted file mode 100644 index 20eec60f14..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/CustomQualifierExampleService.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * An {@link ExampleService} that uses a custom qualifier. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@CustomQualifier -public class CustomQualifierExampleService implements ExampleService { - - @Override - public String greeting() { - return "CustomQualifier"; - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleExtraInterface.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleExtraInterface.java deleted file mode 100644 index 3b5371c6ff..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleExtraInterface.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example extra interface for mocking tests. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@Deprecated(since = "3.4.0", forRemoval = true) -public interface ExampleExtraInterface { - - String doExtra(); - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericService.java deleted file mode 100644 index b8c43ee164..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericService.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example service interface for mocking tests. - * - * @param the generic type - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@Deprecated(since = "3.4.0", forRemoval = true) -public interface ExampleGenericService { - - T greeting(); - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java deleted file mode 100644 index f199167d08..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericServiceCaller.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example bean for mocking tests that calls {@link ExampleGenericService}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class ExampleGenericServiceCaller { - - private final ExampleGenericService integerService; - - private final ExampleGenericService stringService; - - public ExampleGenericServiceCaller(ExampleGenericService integerService, - ExampleGenericService stringService) { - this.integerService = integerService; - this.stringService = stringService; - } - - public ExampleGenericService getIntegerService() { - return this.integerService; - } - - public ExampleGenericService getStringService() { - return this.stringService; - } - - public String sayGreeting() { - return "I say " + this.integerService.greeting() + " " + this.stringService.greeting(); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java deleted file mode 100644 index 43e5eb7140..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleGenericStringServiceCaller.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example bean for mocking tests that calls {@link ExampleGenericService}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class ExampleGenericStringServiceCaller { - - private final ExampleGenericService stringService; - - public ExampleGenericStringServiceCaller(ExampleGenericService stringService) { - this.stringService = stringService; - } - - public ExampleGenericService getStringService() { - return this.stringService; - } - - public String sayGreeting() { - return "I say " + this.stringService.greeting(); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleService.java deleted file mode 100644 index e23b08fcb9..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleService.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example service interface for mocking tests. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@Deprecated(since = "3.4.0", forRemoval = true) -public interface ExampleService { - - String greeting(); - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleServiceCaller.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleServiceCaller.java deleted file mode 100644 index 1b09ab593f..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/ExampleServiceCaller.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example bean for mocking tests that calls {@link ExampleService}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class ExampleServiceCaller { - - private final ExampleService service; - - public ExampleServiceCaller(ExampleService service) { - this.service = service; - } - - public ExampleService getService() { - return this.service; - } - - public String sayGreeting() { - return "I say " + this.service.greeting(); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/FailingExampleService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/FailingExampleService.java deleted file mode 100644 index 5669aea08e..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/FailingExampleService.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -import org.springframework.stereotype.Service; - -/** - * An {@link ExampleService} that always throws an exception. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@Service -public class FailingExampleService implements ExampleService { - - @Override - public String greeting() { - throw new IllegalStateException("Failed"); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/RealExampleService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/RealExampleService.java deleted file mode 100644 index 7cdddd9432..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/RealExampleService.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example service implementation for spy tests. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class RealExampleService implements ExampleService { - - private final String greeting; - - public RealExampleService(String greeting) { - this.greeting = greeting; - } - - @Override - public String greeting() { - return this.greeting; - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java deleted file mode 100644 index 985bc624ea..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleIntegerGenericService.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example generic service implementation for spy tests. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class SimpleExampleIntegerGenericService implements ExampleGenericService { - - @Override - public Integer greeting() { - return 123; - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleService.java deleted file mode 100644 index c4cbd52e7a..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleService.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example service implementation for spy tests. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class SimpleExampleService extends RealExampleService { - - public SimpleExampleService() { - super("simple"); - } - -} diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleStringGenericService.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleStringGenericService.java deleted file mode 100644 index f216be45c8..0000000000 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/example/SimpleExampleStringGenericService.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.test.mock.mockito.example; - -/** - * Example generic service implementation for spy tests. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class SimpleExampleStringGenericService implements ExampleGenericService { - - private final String greeting; - - public SimpleExampleStringGenericService() { - this("simple"); - } - - public SimpleExampleStringGenericService(String greeting) { - this.greeting = greeting; - } - - @Override - public String greeting() { - return this.greeting; - } - -} diff --git a/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationTests.java b/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationTests.java index 10ddb2f93f..1948ec670b 100644 --- a/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.boot.testcontainers.properties; -import java.util.ArrayList; -import java.util.List; - import com.redis.testcontainers.RedisContainer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -32,7 +29,6 @@ import org.springframework.boot.testsupport.container.DisabledIfDockerUnavailabl import org.springframework.boot.testsupport.container.TestImage; import org.springframework.boot.testsupport.system.CapturedOutput; import org.springframework.boot.testsupport.system.OutputCaptureExtension; -import org.springframework.context.ApplicationEvent; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -55,59 +51,6 @@ class TestcontainersPropertySourceAutoConfigurationTests { .withInitializer(new TestcontainersLifecycleApplicationContextInitializer()) .withConfiguration(AutoConfigurations.of(TestcontainersPropertySourceAutoConfiguration.class)); - @Test - @SuppressWarnings("removal") - @Deprecated(since = "3.4.0", forRemoval = true) - void registeringADynamicPropertyFailsByDefault() { - this.contextRunner.withUserConfiguration(ContainerAndPropertiesConfiguration.class) - .run((context) -> assertThat(context).getFailure() - .rootCause() - .isInstanceOf( - org.springframework.boot.testcontainers.properties.TestcontainersPropertySource.DynamicPropertyRegistryInjectionException.class) - .hasMessageStartingWith( - "Support for injecting a DynamicPropertyRegistry into @Bean methods is deprecated")); - } - - @Test - @SuppressWarnings("removal") - @Deprecated(since = "3.4.0", forRemoval = true) - void registeringADynamicPropertyCanLogAWarningAndContributeProperty(CapturedOutput output) { - List events = new ArrayList<>(); - this.contextRunner.withPropertyValues("spring.testcontainers.dynamic-property-registry-injection=warn") - .withUserConfiguration(ContainerAndPropertiesConfiguration.class) - .withInitializer((context) -> context.addApplicationListener(events::add)) - .run((context) -> { - TestBean testBean = context.getBean(TestBean.class); - RedisContainer redisContainer = context.getBean(RedisContainer.class); - assertThat(testBean.getUsingPort()).isEqualTo(redisContainer.getFirstMappedPort()); - assertThat(events.stream() - .filter(org.springframework.boot.testcontainers.lifecycle.BeforeTestcontainerUsedEvent.class::isInstance)) - .hasSize(1); - assertThat(output) - .contains("Support for injecting a DynamicPropertyRegistry into @Bean methods is deprecated"); - }); - } - - @Test - @SuppressWarnings("removal") - @Deprecated(since = "3.4.0", forRemoval = true) - void registeringADynamicPropertyCanBePermittedAndContributeProperty(CapturedOutput output) { - List events = new ArrayList<>(); - this.contextRunner.withPropertyValues("spring.testcontainers.dynamic-property-registry-injection=allow") - .withUserConfiguration(ContainerAndPropertiesConfiguration.class) - .withInitializer((context) -> context.addApplicationListener(events::add)) - .run((context) -> { - TestBean testBean = context.getBean(TestBean.class); - RedisContainer redisContainer = context.getBean(RedisContainer.class); - assertThat(testBean.getUsingPort()).isEqualTo(redisContainer.getFirstMappedPort()); - assertThat(events.stream() - .filter(org.springframework.boot.testcontainers.lifecycle.BeforeTestcontainerUsedEvent.class::isInstance)) - .hasSize(1); - assertThat(output) - .doesNotContain("Support for injecting a DynamicPropertyRegistry into @Bean methods is deprecated"); - }); - } - @Test void dynamicPropertyRegistrarBeanContributesProperties(CapturedOutput output) { this.contextRunner.withUserConfiguration(ContainerAndPropertyRegistrarConfiguration.class).run((context) -> { diff --git a/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationWithSpringBootTestIntegrationTest.java b/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationWithSpringBootTestIntegrationTest.java index ea791d179c..7fc6336742 100644 --- a/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationWithSpringBootTestIntegrationTest.java +++ b/spring-boot-project/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfigurationWithSpringBootTestIntegrationTest.java @@ -27,7 +27,6 @@ import org.springframework.boot.testcontainers.properties.TestcontainersProperty import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.test.context.DynamicPropertyRegistrar; -import org.springframework.test.context.DynamicPropertyRegistry; import static org.assertj.core.api.Assertions.assertThat; @@ -45,11 +44,6 @@ class TestcontainersPropertySourceAutoConfigurationWithSpringBootTestIntegration @Autowired private Environment environment; - @Test - void injectsRegistryIntoBeanMethod() { - assertThat(this.environment.getProperty("from.bean.method")).isEqualTo("one"); - } - @Test void callsRegistrars() { assertThat(this.environment.getProperty("from.registrar")).isEqualTo("two"); @@ -60,12 +54,6 @@ class TestcontainersPropertySourceAutoConfigurationWithSpringBootTestIntegration @SpringBootConfiguration static class TestConfig { - @Bean - String example(DynamicPropertyRegistry registry) { - registry.add("from.bean.method", () -> "one"); - return "Hello"; - } - @Bean DynamicPropertyRegistrar propertyRegistrar() { return (registry) -> registry.add("from.registrar", () -> "two"); diff --git a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/BeforeTestcontainerUsedEvent.java b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/BeforeTestcontainerUsedEvent.java deleted file mode 100644 index 9b74b7f61f..0000000000 --- a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/BeforeTestcontainerUsedEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testcontainers.lifecycle; - -import org.testcontainers.containers.Container; - -import org.springframework.context.ApplicationEvent; -import org.springframework.test.context.DynamicPropertyRegistrar; - -/** - * Event published just before a Testcontainers {@link Container} is used. - * - * @author Andy Wilkinson - * @since 3.2.6 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of property registration using a - * {@link DynamicPropertyRegistrar} bean that injects the {@link Container} from which the - * properties will be sourced. - */ -@Deprecated(since = "3.4.0", forRemoval = true) -public class BeforeTestcontainerUsedEvent extends ApplicationEvent { - - public BeforeTestcontainerUsedEvent(Object source) { - super(source); - } - -} diff --git a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleApplicationContextInitializer.java b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleApplicationContextInitializer.java index 662be02a7f..e5b570c47b 100644 --- a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleApplicationContextInitializer.java +++ b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,6 @@ public class TestcontainersLifecycleApplicationContextInitializer TestcontainersLifecycleBeanPostProcessor beanPostProcessor = new TestcontainersLifecycleBeanPostProcessor( beanFactory, startup); beanFactory.addBeanPostProcessor(beanPostProcessor); - applicationContext.addApplicationListener(beanPostProcessor); } } diff --git a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleBeanPostProcessor.java b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleBeanPostProcessor.java index a09d7906c9..21ca7570a4 100644 --- a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleBeanPostProcessor.java +++ b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,6 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; -import org.springframework.context.ApplicationListener; import org.springframework.context.aot.AbstractAotProcessor; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @@ -59,10 +58,8 @@ import org.springframework.core.log.LogMessage; * @author Scott Frederick * @see TestcontainersLifecycleApplicationContextInitializer */ -@SuppressWarnings({ "removal", "deprecation" }) @Order(Ordered.LOWEST_PRECEDENCE) -class TestcontainersLifecycleBeanPostProcessor - implements DestructionAwareBeanPostProcessor, ApplicationListener { +class TestcontainersLifecycleBeanPostProcessor implements DestructionAwareBeanPostProcessor { private static final Log logger = LogFactory.getLog(TestcontainersLifecycleBeanPostProcessor.class); @@ -80,12 +77,6 @@ class TestcontainersLifecycleBeanPostProcessor this.startup = startup; } - @Override - @Deprecated(since = "3.4.0", forRemoval = true) - public void onApplicationEvent(BeforeTestcontainerUsedEvent event) { - initializeContainers(); - } - @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (this.beanFactory.isConfigurationFrozen() && !isAotProcessingInProgress()) { diff --git a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySource.java b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySource.java deleted file mode 100644 index b48e3fdcf7..0000000000 --- a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySource.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testcontainers.properties; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.function.Supplier; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testcontainers.containers.Container; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.boot.context.properties.bind.BindResult; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.testcontainers.lifecycle.BeforeTestcontainerUsedEvent; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.ApplicationEventPublisherAware; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.EnumerablePropertySource; -import org.springframework.core.env.Environment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.test.context.DynamicPropertyRegistrar; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.util.Assert; -import org.springframework.util.function.SupplierUtils; - -/** - * {@link EnumerablePropertySource} backed by a map with values supplied from one or more - * {@link Container testcontainers}. - * - * @author Phillip Webb - * @since 3.1.0 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of declaring one or more - * {@link DynamicPropertyRegistrar} beans. - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -public class TestcontainersPropertySource extends MapPropertySource { - - private static final Log logger = LogFactory.getLog(TestcontainersPropertySource.class); - - static final String NAME = "testcontainersPropertySource"; - - private final DynamicPropertyRegistry registry; - - private final Set eventPublishers = new CopyOnWriteArraySet<>(); - - TestcontainersPropertySource(DynamicPropertyRegistryInjection registryInjection) { - this(Collections.synchronizedMap(new LinkedHashMap<>()), registryInjection); - } - - private TestcontainersPropertySource(Map> valueSuppliers, - DynamicPropertyRegistryInjection registryInjection) { - super(NAME, Collections.unmodifiableMap(valueSuppliers)); - this.registry = (name, valueSupplier) -> { - Assert.hasText(name, "'name' must not be empty"); - DynamicPropertyRegistryInjectionException.throwIfNecessary(name, registryInjection); - Assert.notNull(valueSupplier, "'valueSupplier' must not be null"); - valueSuppliers.put(name, valueSupplier); - }; - } - - private void addEventPublisher(ApplicationEventPublisher eventPublisher) { - this.eventPublishers.add(eventPublisher); - } - - @Override - public Object getProperty(String name) { - Object valueSupplier = this.source.get(name); - return (valueSupplier != null) ? getProperty(name, valueSupplier) : null; - } - - private Object getProperty(String name, Object valueSupplier) { - BeforeTestcontainerUsedEvent event = new BeforeTestcontainerUsedEvent(this); - this.eventPublishers.forEach((eventPublisher) -> eventPublisher.publishEvent(event)); - return SupplierUtils.resolve(valueSupplier); - } - - public static DynamicPropertyRegistry attach(Environment environment) { - return attach(environment, null); - } - - static DynamicPropertyRegistry attach(ConfigurableApplicationContext applicationContext) { - return attach(applicationContext.getEnvironment(), applicationContext, null); - } - - public static DynamicPropertyRegistry attach(Environment environment, BeanDefinitionRegistry registry) { - return attach(environment, null, registry); - } - - private static DynamicPropertyRegistry attach(Environment environment, ApplicationEventPublisher eventPublisher, - BeanDefinitionRegistry registry) { - Assert.state(environment instanceof ConfigurableEnvironment, - "TestcontainersPropertySource can only be attached to a ConfigurableEnvironment"); - TestcontainersPropertySource propertySource = getOrAdd((ConfigurableEnvironment) environment); - if (eventPublisher != null) { - propertySource.addEventPublisher(eventPublisher); - } - else if (registry != null && !registry.containsBeanDefinition(EventPublisherRegistrar.NAME)) { - registry.registerBeanDefinition(EventPublisherRegistrar.NAME, new RootBeanDefinition( - EventPublisherRegistrar.class, () -> new EventPublisherRegistrar(environment))); - } - return propertySource.registry; - } - - static TestcontainersPropertySource getOrAdd(ConfigurableEnvironment environment) { - PropertySource propertySource = environment.getPropertySources().get(NAME); - if (propertySource == null) { - BindResult bindingResult = Binder.get(environment) - .bind("spring.testcontainers.dynamic-property-registry-injection", - DynamicPropertyRegistryInjection.class); - environment.getPropertySources() - .addFirst( - new TestcontainersPropertySource(bindingResult.orElse(DynamicPropertyRegistryInjection.FAIL))); - return getOrAdd(environment); - } - Assert.state(propertySource instanceof TestcontainersPropertySource, - "Incorrect TestcontainersPropertySource type registered"); - return ((TestcontainersPropertySource) propertySource); - } - - /** - * {@link BeanFactoryPostProcessor} to register the {@link ApplicationEventPublisher} - * to the {@link TestcontainersPropertySource}. This class is a - * {@link BeanFactoryPostProcessor} so that it is initialized as early as possible. - */ - static class EventPublisherRegistrar implements BeanFactoryPostProcessor, ApplicationEventPublisherAware { - - static final String NAME = EventPublisherRegistrar.class.getName(); - - private final Environment environment; - - private ApplicationEventPublisher eventPublisher; - - EventPublisherRegistrar(Environment environment) { - this.environment = environment; - } - - @Override - public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) { - this.eventPublisher = eventPublisher; - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - if (this.eventPublisher != null) { - TestcontainersPropertySource.getOrAdd((ConfigurableEnvironment) this.environment) - .addEventPublisher(this.eventPublisher); - } - } - - } - - private enum DynamicPropertyRegistryInjection { - - ALLOW, - - FAIL, - - WARN - - } - - static final class DynamicPropertyRegistryInjectionException extends RuntimeException { - - private DynamicPropertyRegistryInjectionException(String propertyName) { - super("Support for injecting a DynamicPropertyRegistry into @Bean methods is deprecated. Register '" - + propertyName + "' using a DynamicPropertyRegistrar bean instead. Alternatively, set " - + "spring.testcontainers.dynamic-property-registry-injection to 'warn' to replace this " - + "failure with a warning or to 'allow' to permit injection of the registry."); - } - - private static void throwIfNecessary(String propertyName, DynamicPropertyRegistryInjection registryInjection) { - switch (registryInjection) { - case FAIL -> throw new DynamicPropertyRegistryInjectionException(propertyName); - case WARN -> logger - .warn("Support for injecting a DynamicPropertyRegistry into @Bean methods is deprecated. Register '" - + propertyName + "' using a DynamicPropertyRegistrar bean instead."); - } - } - - } - -} diff --git a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfiguration.java b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfiguration.java index 0d6271906a..9b8cb27b48 100644 --- a/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfiguration.java +++ b/spring-boot-project/spring-boot-testcontainers/src/main/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Role; import org.springframework.core.Ordered; @@ -44,13 +43,6 @@ import org.springframework.test.context.support.DynamicPropertyRegistrarBeanInit @ConditionalOnClass(DynamicPropertyRegistry.class) public class TestcontainersPropertySourceAutoConfiguration { - @Bean - @SuppressWarnings("removal") - @Deprecated(since = "3.4.0", forRemoval = true) - static DynamicPropertyRegistry dynamicPropertyRegistry(ConfigurableApplicationContext applicationContext) { - return TestcontainersPropertySource.attach(applicationContext); - } - @Bean @ConditionalOnMissingBean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) diff --git a/spring-boot-project/spring-boot-testcontainers/src/test/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceTests.java b/spring-boot-project/spring-boot-testcontainers/src/test/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceTests.java deleted file mode 100644 index 2621b47df1..0000000000 --- a/spring-boot-project/spring-boot-testcontainers/src/test/java/org/springframework/boot/testcontainers/properties/TestcontainersPropertySourceTests.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.testcontainers.properties; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.boot.testcontainers.lifecycle.BeforeTestcontainerUsedEvent; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.EnumerablePropertySource; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.mock.env.MockEnvironment; -import org.springframework.test.context.DynamicPropertyRegistry; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -/** - * Tests for {@link TestcontainersPropertySource}. - * - * @author Phillip Webb - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -class TestcontainersPropertySourceTests { - - private MockEnvironment environment = new MockEnvironment() - .withProperty("spring.testcontainers.dynamic-property-registry-injection", "allow"); - - private GenericApplicationContext context = new GenericApplicationContext(); - - TestcontainersPropertySourceTests() { - ((DefaultListableBeanFactory) this.context.getBeanFactory()).setAllowBeanDefinitionOverriding(false); - this.context.setEnvironment(this.environment); - } - - @Test - void getPropertyWhenHasValueSupplierReturnsSuppliedValue() { - DynamicPropertyRegistry registry = TestcontainersPropertySource.attach(this.environment); - registry.add("test", () -> "spring"); - assertThat(this.environment.getProperty("test")).isEqualTo("spring"); - } - - @Test - void getPropertyWhenHasNoValueSupplierReturnsNull() { - DynamicPropertyRegistry registry = TestcontainersPropertySource.attach(this.environment); - registry.add("test", () -> "spring"); - assertThat(this.environment.getProperty("missing")).isNull(); - } - - @Test - void containsPropertyWhenHasPropertyReturnsTrue() { - DynamicPropertyRegistry registry = TestcontainersPropertySource.attach(this.environment); - registry.add("test", () -> null); - assertThat(this.environment.containsProperty("test")).isTrue(); - } - - @Test - void containsPropertyWhenHasNoPropertyReturnsFalse() { - DynamicPropertyRegistry registry = TestcontainersPropertySource.attach(this.environment); - registry.add("test", () -> null); - assertThat(this.environment.containsProperty("missing")).isFalse(); - } - - @Test - void getPropertyNamesReturnsNames() { - DynamicPropertyRegistry registry = TestcontainersPropertySource.attach(this.environment); - registry.add("test", () -> null); - registry.add("other", () -> null); - EnumerablePropertySource propertySource = (EnumerablePropertySource) this.environment.getPropertySources() - .get(TestcontainersPropertySource.NAME); - assertThat(propertySource.getPropertyNames()).containsExactly("test", "other"); - } - - @Test - @SuppressWarnings("unchecked") - void getSourceReturnsImmutableSource() { - TestcontainersPropertySource.attach(this.environment); - PropertySource propertySource = this.environment.getPropertySources().get(TestcontainersPropertySource.NAME); - Map map = (Map) propertySource.getSource(); - assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(map::clear); - } - - @Test - void attachToEnvironmentWhenNotAttachedAttaches() { - TestcontainersPropertySource.attach(this.environment); - PropertySource propertySource = this.environment.getPropertySources().get(TestcontainersPropertySource.NAME); - assertThat(propertySource).isNotNull(); - } - - @Test - void attachToEnvironmentWhenAlreadyAttachedReturnsExisting() { - DynamicPropertyRegistry r1 = TestcontainersPropertySource.attach(this.environment); - PropertySource p1 = this.environment.getPropertySources().get(TestcontainersPropertySource.NAME); - DynamicPropertyRegistry r2 = TestcontainersPropertySource.attach(this.environment); - PropertySource p2 = this.environment.getPropertySources().get(TestcontainersPropertySource.NAME); - assertThat(r1).isSameAs(r2); - assertThat(p1).isSameAs(p2); - } - - @Test - void attachToEnvironmentAndContextWhenNotAttachedAttaches() { - TestcontainersPropertySource.attach(this.environment, this.context); - PropertySource propertySource = this.environment.getPropertySources().get(TestcontainersPropertySource.NAME); - assertThat(propertySource).isNotNull(); - assertThat(this.context.containsBean( - org.springframework.boot.testcontainers.properties.TestcontainersPropertySource.EventPublisherRegistrar.NAME)); - } - - @Test - void attachToEnvironmentAndContextWhenAlreadyAttachedReturnsExisting() { - DynamicPropertyRegistry r1 = TestcontainersPropertySource.attach(this.environment, this.context); - PropertySource p1 = this.environment.getPropertySources().get(TestcontainersPropertySource.NAME); - DynamicPropertyRegistry r2 = TestcontainersPropertySource.attach(this.environment, this.context); - PropertySource p2 = this.environment.getPropertySources().get(TestcontainersPropertySource.NAME); - assertThat(r1).isSameAs(r2); - assertThat(p1).isSameAs(p2); - } - - @Test - void getPropertyPublishesEvent() { - try (GenericApplicationContext applicationContext = new GenericApplicationContext()) { - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - environment.getPropertySources() - .addLast(new MapPropertySource("test", - Map.of("spring.testcontainers.dynamic-property-registry-injection", "allow"))); - List events = new ArrayList<>(); - applicationContext.addApplicationListener(events::add); - DynamicPropertyRegistry registry = TestcontainersPropertySource.attach(environment, - (BeanDefinitionRegistry) applicationContext.getBeanFactory()); - applicationContext.refresh(); - registry.add("test", () -> "spring"); - assertThat(environment.containsProperty("test")).isTrue(); - assertThat(events.isEmpty()); - assertThat(environment.getProperty("test")).isEqualTo("spring"); - assertThat(events.stream().filter(BeforeTestcontainerUsedEvent.class::isInstance)).hasSize(1); - } - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Builder.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Builder.java index 3d3b81ebfb..b23de8fb6d 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Builder.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Builder.java @@ -26,7 +26,6 @@ import org.springframework.boot.buildpack.platform.docker.TotalProgressEvent; import org.springframework.boot.buildpack.platform.docker.TotalProgressPullListener; import org.springframework.boot.buildpack.platform.docker.TotalProgressPushListener; import org.springframework.boot.buildpack.platform.docker.UpdateListener; -import org.springframework.boot.buildpack.platform.docker.configuration.DockerConnectionConfiguration; import org.springframework.boot.buildpack.platform.docker.configuration.DockerRegistryAuthentication; import org.springframework.boot.buildpack.platform.docker.configuration.ResolvedDockerHost; import org.springframework.boot.buildpack.platform.docker.transport.DockerEngineException; @@ -64,20 +63,6 @@ public class Builder { this(BuildLog.toSystemOut()); } - /** - * Create a new builder instance. - * @param dockerConfiguration the docker configuration - * @since 2.4.0 - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #Builder(BuilderDockerConfiguration)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - @SuppressWarnings("removal") - public Builder( - org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration dockerConfiguration) { - this(BuildLog.toSystemOut(), dockerConfiguration); - } - /** * Create a new builder instance. * @param dockerConfiguration the docker configuration @@ -95,33 +80,6 @@ public class Builder { this(log, new DockerApi(null, BuildLogAdapter.get(log)), null); } - /** - * Create a new builder instance. - * @param log a logger used to record output - * @param dockerConfiguration the docker configuration - * @since 2.4.0 - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #Builder(BuildLog, BuilderDockerConfiguration)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - @SuppressWarnings("removal") - public Builder(BuildLog log, - org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration dockerConfiguration) { - this(log, adaptDeprecatedConfiguration(dockerConfiguration)); - } - - @SuppressWarnings("removal") - private static BuilderDockerConfiguration adaptDeprecatedConfiguration( - org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration configuration) { - if (configuration == null) { - return null; - } - DockerConnectionConfiguration connection = org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration.DockerHostConfiguration - .asConnectionConfiguration(configuration.getHost()); - return new BuilderDockerConfiguration(connection, configuration.isBindHostToBuilder(), - configuration.getBuilderRegistryAuthentication(), configuration.getPublishRegistryAuthentication()); - } - /** * Create a new builder instance. * @param log a logger used to record output diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java index ed8b88decc..b984b8539a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/DockerApi.java @@ -90,21 +90,6 @@ public class DockerApi { this(HttpTransport.create((DockerConnectionConfiguration) null), DockerLog.toSystemOut()); } - /** - * Create a new {@link DockerApi} instance. - * @param dockerHost the Docker daemon host information - * @since 2.4.0 - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #DockerApi(DockerConnectionConfiguration, DockerLog)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - @SuppressWarnings("removal") - public DockerApi( - org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration.DockerHostConfiguration dockerHost) { - this(org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration.DockerHostConfiguration - .asConnectionConfiguration(dockerHost), DockerLog.toSystemOut()); - } - /** * Create a new {@link DockerApi} instance. * @param connectionConfiguration the connection configuration to use diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/DockerConfiguration.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/DockerConfiguration.java deleted file mode 100644 index bf6f1ebd8a..0000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/DockerConfiguration.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.buildpack.platform.docker.configuration; - -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -/** - * Docker configuration options. - * - * @author Wei Jiang - * @author Scott Frederick - * @since 2.4.0 - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link org.springframework.boot.buildpack.platform.build.BuilderDockerConfiguration}. - */ -@Deprecated(since = "3.5.0", forRemoval = true) -@SuppressWarnings("removal") -public final class DockerConfiguration { - - private final DockerHostConfiguration host; - - private final DockerRegistryAuthentication builderAuthentication; - - private final DockerRegistryAuthentication publishAuthentication; - - private final boolean bindHostToBuilder; - - public DockerConfiguration() { - this(null, null, null, false); - } - - private DockerConfiguration(DockerHostConfiguration host, DockerRegistryAuthentication builderAuthentication, - DockerRegistryAuthentication publishAuthentication, boolean bindHostToBuilder) { - this.host = host; - this.builderAuthentication = builderAuthentication; - this.publishAuthentication = publishAuthentication; - this.bindHostToBuilder = bindHostToBuilder; - } - - public DockerHostConfiguration getHost() { - return this.host; - } - - public boolean isBindHostToBuilder() { - return this.bindHostToBuilder; - } - - public DockerRegistryAuthentication getBuilderRegistryAuthentication() { - return this.builderAuthentication; - } - - public DockerRegistryAuthentication getPublishRegistryAuthentication() { - return this.publishAuthentication; - } - - public DockerConfiguration withHost(String address, boolean secure, String certificatePath) { - Assert.notNull(address, "'address' must not be null"); - return new DockerConfiguration(DockerHostConfiguration.forAddress(address, secure, certificatePath), - this.builderAuthentication, this.publishAuthentication, this.bindHostToBuilder); - } - - public DockerConfiguration withContext(String context) { - Assert.notNull(context, "'context' must not be null"); - return new DockerConfiguration(DockerHostConfiguration.forContext(context), this.builderAuthentication, - this.publishAuthentication, this.bindHostToBuilder); - } - - public DockerConfiguration withBindHostToBuilder(boolean bindHostToBuilder) { - return new DockerConfiguration(this.host, this.builderAuthentication, this.publishAuthentication, - bindHostToBuilder); - } - - public DockerConfiguration withBuilderRegistryTokenAuthentication(String token) { - Assert.notNull(token, "'token' must not be null"); - return new DockerConfiguration(this.host, new DockerRegistryTokenAuthentication(token), - this.publishAuthentication, this.bindHostToBuilder); - } - - public DockerConfiguration withBuilderRegistryUserAuthentication(String username, String password, String url, - String email) { - Assert.notNull(username, "'username' must not be null"); - Assert.notNull(password, "'password' must not be null"); - return new DockerConfiguration(this.host, new DockerRegistryUserAuthentication(username, password, url, email), - this.publishAuthentication, this.bindHostToBuilder); - } - - public DockerConfiguration withPublishRegistryTokenAuthentication(String token) { - Assert.notNull(token, "'token' must not be null"); - return new DockerConfiguration(this.host, this.builderAuthentication, - new DockerRegistryTokenAuthentication(token), this.bindHostToBuilder); - } - - public DockerConfiguration withPublishRegistryUserAuthentication(String username, String password, String url, - String email) { - Assert.notNull(username, "'username' must not be null"); - Assert.notNull(password, "'password' must not be null"); - return new DockerConfiguration(this.host, this.builderAuthentication, - new DockerRegistryUserAuthentication(username, password, url, email), this.bindHostToBuilder); - } - - public DockerConfiguration withEmptyPublishRegistryAuthentication() { - return new DockerConfiguration(this.host, this.builderAuthentication, - new DockerRegistryUserAuthentication("", "", "", ""), this.bindHostToBuilder); - } - - /** - * Docker host configuration. - * - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link DockerHostConfiguration} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - public static class DockerHostConfiguration { - - private final String address; - - private final String context; - - private final boolean secure; - - private final String certificatePath; - - public DockerHostConfiguration(String address, String context, boolean secure, String certificatePath) { - this.address = address; - this.context = context; - this.secure = secure; - this.certificatePath = certificatePath; - } - - public String getAddress() { - return this.address; - } - - public String getContext() { - return this.context; - } - - public boolean isSecure() { - return this.secure; - } - - public String getCertificatePath() { - return this.certificatePath; - } - - public static DockerHostConfiguration forAddress(String address) { - return new DockerHostConfiguration(address, null, false, null); - } - - public static DockerHostConfiguration forAddress(String address, boolean secure, String certificatePath) { - return new DockerHostConfiguration(address, null, secure, certificatePath); - } - - static DockerHostConfiguration forContext(String context) { - return new DockerHostConfiguration(null, context, false, null); - } - - /** - * Adapts a {@link DockerHostConfiguration} to a - * {@link DockerConnectionConfiguration}. - * @param configuration the configuration to adapt - * @return the adapted configuration - * @since 3.5.0 - */ - public static DockerConnectionConfiguration asConnectionConfiguration(DockerHostConfiguration configuration) { - if (configuration != null && StringUtils.hasLength(configuration.context)) { - return new DockerConnectionConfiguration.Context(configuration.context); - } - if (configuration != null && StringUtils.hasLength(configuration.address)) { - return new DockerConnectionConfiguration.Host(configuration.address, configuration.secure, - configuration.certificatePath); - } - return null; - } - - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/ResolvedDockerHost.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/ResolvedDockerHost.java index cd556c9180..f1110a8563 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/ResolvedDockerHost.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/configuration/ResolvedDockerHost.java @@ -76,20 +76,6 @@ public class ResolvedDockerHost extends DockerHost { } } - /** - * Create a new {@link ResolvedDockerHost} from the given host configuration. - * @param dockerHostConfiguration the host configuration or {@code null} - * @return the resolved docker host - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #from(DockerConnectionConfiguration)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - @SuppressWarnings("removal") - public static ResolvedDockerHost from(DockerConfiguration.DockerHostConfiguration dockerHostConfiguration) { - return from(Environment.SYSTEM, - DockerConfiguration.DockerHostConfiguration.asConnectionConfiguration(dockerHostConfiguration)); - } - /** * Create a new {@link ResolvedDockerHost} from the given host configuration. * @param connectionConfiguration the host configuration or {@code null} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/transport/HttpTransport.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/transport/HttpTransport.java index 0224707ff7..71405a29c3 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/transport/HttpTransport.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/transport/HttpTransport.java @@ -99,22 +99,6 @@ public interface HttpTransport { */ Response head(URI uri) throws IOException; - /** - * Create the most suitable {@link HttpTransport} based on the {@link DockerHost}. - * @param dockerHost the Docker host information - * @return a {@link HttpTransport} instance - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #create(DockerConnectionConfiguration)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - @SuppressWarnings("removal") - static HttpTransport create( - org.springframework.boot.buildpack.platform.docker.configuration.DockerConfiguration.DockerHostConfiguration dockerHost) { - ResolvedDockerHost host = ResolvedDockerHost.from(dockerHost); - HttpTransport remote = RemoteHttpClientTransport.createIfPossible(host); - return (remote != null) ? remote : LocalHttpClientTransport.create(host); - } - /** * Create the most suitable {@link HttpTransport} based on the {@link DockerHost}. * @param connectionConfiguration the Docker host information diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/configuration/DockerConfigurationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/configuration/DockerConfigurationTests.java deleted file mode 100644 index d61cac68be..0000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/configuration/DockerConfigurationTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.buildpack.platform.docker.configuration; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link DockerConfiguration}. - * - * @author Wei Jiang - * @author Scott Frederick - */ -@SuppressWarnings("removal") -class DockerConfigurationTests { - - @Test - void createDockerConfigurationWithDefaults() { - DockerConfiguration configuration = new DockerConfiguration(); - assertThat(configuration.getBuilderRegistryAuthentication()).isNull(); - } - - @Test - void createDockerConfigurationWithUserAuth() { - DockerConfiguration configuration = new DockerConfiguration().withBuilderRegistryUserAuthentication("user", - "secret", "https://docker.example.com", "docker@example.com"); - DockerRegistryAuthentication auth = configuration.getBuilderRegistryAuthentication(); - assertThat(auth).isNotNull(); - assertThat(auth).isInstanceOf(DockerRegistryUserAuthentication.class); - DockerRegistryUserAuthentication userAuth = (DockerRegistryUserAuthentication) auth; - assertThat(userAuth.getUrl()).isEqualTo("https://docker.example.com"); - assertThat(userAuth.getUsername()).isEqualTo("user"); - assertThat(userAuth.getPassword()).isEqualTo("secret"); - assertThat(userAuth.getEmail()).isEqualTo("docker@example.com"); - } - - @Test - void createDockerConfigurationWithTokenAuth() { - DockerConfiguration configuration = new DockerConfiguration().withBuilderRegistryTokenAuthentication("token"); - DockerRegistryAuthentication auth = configuration.getBuilderRegistryAuthentication(); - assertThat(auth).isNotNull(); - assertThat(auth).isInstanceOf(DockerRegistryTokenAuthentication.class); - DockerRegistryTokenAuthentication tokenAuth = (DockerRegistryTokenAuthentication) auth; - assertThat(tokenAuth.getToken()).isEqualTo("token"); - } - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java index 1a39c885f7..343c142427 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessor.java @@ -47,7 +47,6 @@ import javax.tools.Diagnostic.Kind; import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata; import org.springframework.boot.configurationprocessor.metadata.InvalidConfigurationMetadataException; -import org.springframework.boot.configurationprocessor.metadata.ItemDeprecation; import org.springframework.boot.configurationprocessor.metadata.ItemHint; import org.springframework.boot.configurationprocessor.metadata.ItemIgnore; import org.springframework.boot.configurationprocessor.metadata.ItemMetadata; @@ -346,19 +345,13 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor return; // Can't process that endpoint } String endpointKey = ItemMetadata.newItemMetadataPrefix("management.endpoint.", endpointId); - boolean enabledByDefaultAttribute = (boolean) elementValues.getOrDefault("enableByDefault", true); - String defaultAccess = (!enabledByDefaultAttribute) ? "none" - : (elementValues.getOrDefault("defaultAccess", "unrestricted").toString()).toLowerCase(Locale.ENGLISH); - boolean enabledByDefault = !"none".equals(defaultAccess) && enabledByDefaultAttribute; + String defaultAccess = elementValues.getOrDefault("defaultAccess", "unrestricted") + .toString() + .toLowerCase(Locale.ENGLISH); String type = this.metadataEnv.getTypeUtils().getQualifiedName(element); this.metadataCollector.addIfAbsent(ItemMetadata.newGroup(endpointKey, type, type, null)); ItemMetadata accessProperty = ItemMetadata.newProperty(endpointKey, "access", endpointAccessEnum(), type, null, "Permitted level of access for the %s endpoint.".formatted(endpointId), defaultAccess, null); - this.metadataCollector.add( - ItemMetadata.newProperty(endpointKey, "enabled", Boolean.class.getName(), type, null, - "Whether to enable the %s endpoint.".formatted(endpointId), enabledByDefault, - new ItemDeprecation(null, accessProperty.getName(), "3.4.0")), - (existing) -> checkEnabledValueMatchesExisting(existing, enabledByDefault, type)); this.metadataCollector.add(accessProperty, (existing) -> checkDefaultAccessValueMatchesExisting(existing, defaultAccess, type)); if (hasMainReadOperation(element)) { @@ -367,22 +360,12 @@ public class ConfigurationMetadataAnnotationProcessor extends AbstractProcessor } } - private void checkEnabledValueMatchesExisting(ItemMetadata existing, boolean enabledByDefault, String sourceType) { - boolean existingDefaultValue = (boolean) existing.getDefaultValue(); - if (enabledByDefault != existingDefaultValue) { - throw new IllegalStateException( - "Existing property '%s' from type %s has a conflicting value. Existing value: %b, new value from type %s: %b" - .formatted(existing.getName(), existing.getSourceType(), existingDefaultValue, sourceType, - enabledByDefault)); - } - } - private void checkDefaultAccessValueMatchesExisting(ItemMetadata existing, String defaultAccess, String sourceType) { String existingDefaultAccess = (String) existing.getDefaultValue(); if (!Objects.equals(defaultAccess, existingDefaultAccess)) { throw new IllegalStateException( - "Existing property '%s' from type %s has a conflicting value. Existing value: %b, new value from type %s: %b" + "Existing property '%s' from type %s has a conflicting value. Existing value: %s, new value from type %s: %s" .formatted(existing.getName(), existing.getSourceType(), existingDefaultAccess, sourceType, defaultAccess)); } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java index ecde354bb4..86b512a619 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/EndpointMetadataGenerationTests.java @@ -26,7 +26,6 @@ import org.springframework.boot.configurationprocessor.metadata.Metadata; import org.springframework.boot.configurationsample.Access; import org.springframework.boot.configurationsample.endpoint.CamelCaseEndpoint; import org.springframework.boot.configurationsample.endpoint.CustomPropertiesEndpoint; -import org.springframework.boot.configurationsample.endpoint.DisabledEndpoint; import org.springframework.boot.configurationsample.endpoint.EnabledEndpoint; import org.springframework.boot.configurationsample.endpoint.NoAccessEndpoint; import org.springframework.boot.configurationsample.endpoint.ReadOnlyAccessEndpoint; @@ -53,18 +52,8 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { void simpleEndpoint() { ConfigurationMetadata metadata = compile(SimpleEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple").fromSource(SimpleEndpoint.class)); - assertThat(metadata).has(enabledFlag("simple", true)); assertThat(metadata).has(access("simple", Access.UNRESTRICTED)); assertThat(metadata).has(cacheTtl("simple")); - assertThat(metadata.getItems()).hasSize(4); - } - - @Test - void disabledEndpoint() { - ConfigurationMetadata metadata = compile(DisabledEndpoint.class); - assertThat(metadata).has(Metadata.withGroup("management.endpoint.disabled").fromSource(DisabledEndpoint.class)); - assertThat(metadata).has(enabledFlag("disabled", false)); - assertThat(metadata).has(access("disabled", Access.NONE)); assertThat(metadata.getItems()).hasSize(3); } @@ -72,18 +61,16 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { void enabledEndpoint() { ConfigurationMetadata metadata = compile(EnabledEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.enabled").fromSource(EnabledEndpoint.class)); - assertThat(metadata).has(enabledFlag("enabled", true)); assertThat(metadata).has(access("enabled", Access.UNRESTRICTED)); - assertThat(metadata.getItems()).hasSize(3); + assertThat(metadata.getItems()).hasSize(2); } @Test void noAccessEndpoint() { ConfigurationMetadata metadata = compile(NoAccessEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.noaccess").fromSource(NoAccessEndpoint.class)); - assertThat(metadata).has(enabledFlag("noaccess", false)); assertThat(metadata).has(access("noaccess", Access.NONE)); - assertThat(metadata.getItems()).hasSize(3); + assertThat(metadata.getItems()).hasSize(2); } @Test @@ -91,9 +78,8 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(ReadOnlyAccessEndpoint.class); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.readonlyaccess").fromSource(ReadOnlyAccessEndpoint.class)); - assertThat(metadata).has(enabledFlag("readonlyaccess", true)); assertThat(metadata).has(access("readonlyaccess", Access.READ_ONLY)); - assertThat(metadata.getItems()).hasSize(3); + assertThat(metadata.getItems()).hasSize(2); } @Test @@ -101,9 +87,8 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(UnrestrictedAccessEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.unrestrictedaccess") .fromSource(UnrestrictedAccessEndpoint.class)); - assertThat(metadata).has(enabledFlag("unrestrictedaccess", true)); assertThat(metadata).has(access("unrestrictedaccess", Access.UNRESTRICTED)); - assertThat(metadata.getItems()).hasSize(3); + assertThat(metadata.getItems()).hasSize(2); } @Test @@ -114,20 +99,18 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { assertThat(metadata).has(Metadata.withProperty("management.endpoint.customprops.name") .ofType(String.class) .withDefaultValue("test")); - assertThat(metadata).has(enabledFlag("customprops", true)); assertThat(metadata).has(access("customprops", Access.UNRESTRICTED)); assertThat(metadata).has(cacheTtl("customprops")); - assertThat(metadata.getItems()).hasSize(5); + assertThat(metadata.getItems()).hasSize(4); } @Test void specificEndpoint() { ConfigurationMetadata metadata = compile(SpecificEndpoint.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); - assertThat(metadata).has(enabledFlag("specific", true)); - assertThat(metadata).has(access("specific", Access.UNRESTRICTED)); + assertThat(metadata).has(access("specific", Access.READ_ONLY)); assertThat(metadata).has(cacheTtl("specific")); - assertThat(metadata.getItems()).hasSize(4); + assertThat(metadata.getItems()).hasSize(3); } @Test @@ -135,30 +118,27 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = compile(CamelCaseEndpoint.class); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class)); - assertThat(metadata).has(enabledFlag("PascalCase", "pascal-case", true)); assertThat(metadata).has(defaultAccess("PascalCase", "pascal-case", Access.UNRESTRICTED)); - assertThat(metadata.getItems()).hasSize(3); + assertThat(metadata.getItems()).hasSize(2); } @Test - void incrementalEndpointBuildChangeGeneralEnabledFlag() { + void incrementalEndpointBuildChangeDefaultAccess() { TestProject project = new TestProject(IncrementalEndpoint.class); ConfigurationMetadata metadata = project.compile(); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); - assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(access("incremental", Access.UNRESTRICTED)); assertThat(metadata).has(cacheTtl("incremental")); - assertThat(metadata.getItems()).hasSize(4); + assertThat(metadata.getItems()).hasSize(3); project.replaceText(IncrementalEndpoint.class, "id = \"incremental\"", - "id = \"incremental\", enableByDefault = false"); + "id = \"incremental\", defaultAccess = org.springframework.boot.configurationsample.Access.NONE"); metadata = project.compile(); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); - assertThat(metadata).has(enabledFlag("incremental", false)); assertThat(metadata).has(access("incremental", Access.NONE)); assertThat(metadata).has(cacheTtl("incremental")); - assertThat(metadata.getItems()).hasSize(4); + assertThat(metadata.getItems()).hasSize(3); } @Test @@ -167,45 +147,40 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { ConfigurationMetadata metadata = project.compile(); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); - assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(access("incremental", Access.UNRESTRICTED)); assertThat(metadata).has(cacheTtl("incremental")); - assertThat(metadata.getItems()).hasSize(4); + assertThat(metadata.getItems()).hasSize(3); project.replaceText(IncrementalEndpoint.class, "@OptionalParameter String param", "String param"); metadata = project.compile(); assertThat(metadata) .has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class)); - assertThat(metadata).has(enabledFlag("incremental", true)); assertThat(metadata).has(access("incremental", Access.UNRESTRICTED)); - assertThat(metadata.getItems()).hasSize(3); + assertThat(metadata.getItems()).hasSize(2); } @Test - void incrementalEndpointBuildEnableSpecificEndpoint() { + void incrementalEndpointBuildChangeAccessOfSpecificEndpoint() { TestProject project = new TestProject(SpecificEndpoint.class); ConfigurationMetadata metadata = project.compile(); assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); - assertThat(metadata).has(enabledFlag("specific", true)); - assertThat(metadata).has(access("specific", Access.UNRESTRICTED)); + assertThat(metadata).has(access("specific", Access.READ_ONLY)); assertThat(metadata).has(cacheTtl("specific")); - assertThat(metadata.getItems()).hasSize(4); - project.replaceText(SpecificEndpoint.class, "enableByDefault = true", "enableByDefault = false"); + assertThat(metadata.getItems()).hasSize(3); + project.replaceText(SpecificEndpoint.class, "defaultAccess = Access.READ_ONLY", "defaultAccess = Access.NONE"); metadata = project.compile(); assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class)); - assertThat(metadata).has(enabledFlag("specific", false)); assertThat(metadata).has(access("specific", Access.NONE)); assertThat(metadata).has(cacheTtl("specific")); - assertThat(metadata.getItems()).hasSize(4); + assertThat(metadata.getItems()).hasSize(3); } @Test void shouldTolerateEndpointWithSameId() { ConfigurationMetadata metadata = compile(SimpleEndpoint.class, SimpleEndpoint2.class); assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple").fromSource(SimpleEndpoint.class)); - assertThat(metadata).has(enabledFlag("simple", "simple", true)); assertThat(metadata).has(defaultAccess("simple", "simple", Access.UNRESTRICTED)); assertThat(metadata).has(cacheTtl("simple")); - assertThat(metadata.getItems()).hasSize(4); + assertThat(metadata.getItems()).hasSize(3); } @Test @@ -214,18 +189,7 @@ class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests { .havingRootCause() .isInstanceOf(IllegalStateException.class) .withMessage( - "Existing property 'management.endpoint.simple.enabled' from type org.springframework.boot.configurationsample.endpoint.SimpleEndpoint has a conflicting value. Existing value: true, new value from type org.springframework.boot.configurationsample.endpoint.SimpleEndpoint3: false"); - } - - private Metadata.MetadataItemCondition enabledFlag(String endpointId, Boolean defaultValue) { - return enabledFlag(endpointId, endpointId, defaultValue); - } - - private Metadata.MetadataItemCondition enabledFlag(String endpointId, String endpointSuffix, Boolean defaultValue) { - return Metadata.withEnabledFlag("management.endpoint." + endpointSuffix + ".enabled") - .withDefaultValue(defaultValue) - .withDescription(String.format("Whether to enable the %s endpoint.", endpointId)) - .withDeprecation(null, "management.endpoint.%s.access".formatted(endpointSuffix), "3.4.0"); + "Existing property 'management.endpoint.simple.access' from type org.springframework.boot.configurationsample.endpoint.SimpleEndpoint has a conflicting value. Existing value: unrestricted, new value from type org.springframework.boot.configurationsample.endpoint.SimpleEndpoint3: none"); } private Metadata.MetadataItemCondition access(String endpointId, Access defaultValue) { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/Endpoint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/Endpoint.java index 44cc2d9a01..95b1a27f70 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/Endpoint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/Endpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,6 @@ public @interface Endpoint { String id() default ""; - @Deprecated - boolean enableByDefault() default true; - Access defaultAccess() default Access.UNRESTRICTED; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/JmxEndpoint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/JmxEndpoint.java index eba43570eb..0132f0d94a 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/JmxEndpoint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/JmxEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,6 @@ public @interface JmxEndpoint { String id() default ""; - @Deprecated - boolean enableByDefault() default true; - Access defaultAccess() default Access.UNRESTRICTED; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/RestControllerEndpoint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/RestControllerEndpoint.java index 0643a67e1d..cf9650a722 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/RestControllerEndpoint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/RestControllerEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,6 @@ public @interface RestControllerEndpoint { String id() default ""; - @Deprecated - boolean enableByDefault() default true; - Access defaultAccess() default Access.UNRESTRICTED; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/ServletEndpoint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/ServletEndpoint.java index a3c0ccaf7e..b1fab0171f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/ServletEndpoint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/ServletEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,6 @@ public @interface ServletEndpoint { String id() default ""; - @Deprecated - boolean enableByDefault() default true; - Access defaultAccess() default Access.UNRESTRICTED; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/WebEndpoint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/WebEndpoint.java index f40415058f..42db75e538 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/WebEndpoint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/WebEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,6 @@ public @interface WebEndpoint { String id() default ""; - @Deprecated - boolean enableByDefault() default true; - Access defaultAccess() default Access.UNRESTRICTED; } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/DisabledEndpoint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/DisabledEndpoint.java deleted file mode 100644 index 717ed5c24c..0000000000 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/DisabledEndpoint.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2012-2025 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.configurationsample.endpoint; - -import org.springframework.boot.configurationsample.Endpoint; - -/** - * An endpoint that is disabled unless configured explicitly. - * - * @author Stephane Nicoll - */ -@SuppressWarnings({ "deprecation", "removal" }) -@Endpoint(id = "disabled", enableByDefault = false) -public class DisabledEndpoint { - -} diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SimpleEndpoint3.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SimpleEndpoint3.java index 325e1560c3..c147d4f272 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SimpleEndpoint3.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SimpleEndpoint3.java @@ -16,17 +16,17 @@ package org.springframework.boot.configurationsample.endpoint; +import org.springframework.boot.configurationsample.Access; import org.springframework.boot.configurationsample.Endpoint; import org.springframework.boot.configurationsample.ReadOperation; /** * A simple endpoint with no default override, with the same id as {@link SimpleEndpoint}, - * but not enabled by default. + * but with no access by default. * * @author Moritz Halbritter */ -@SuppressWarnings({ "deprecation", "removal" }) -@Endpoint(id = "simple", enableByDefault = false) +@Endpoint(id = "simple", defaultAccess = Access.NONE) public class SimpleEndpoint3 { @ReadOperation diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SpecificEndpoint.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SpecificEndpoint.java index 375c44a4dc..a9c7aa90db 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SpecificEndpoint.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/endpoint/SpecificEndpoint.java @@ -16,6 +16,7 @@ package org.springframework.boot.configurationsample.endpoint; +import org.springframework.boot.configurationsample.Access; import org.springframework.boot.configurationsample.OptionalParameter; import org.springframework.boot.configurationsample.ReadOperation; import org.springframework.boot.configurationsample.WebEndpoint; @@ -26,8 +27,7 @@ import org.springframework.boot.configurationsample.WebEndpoint; * * @author Stephane Nicoll */ -@SuppressWarnings({ "deprecation", "removal" }) -@WebEndpoint(id = "specific", enableByDefault = true) +@WebEndpoint(id = "specific", defaultAccess = Access.READ_ONLY) public class SpecificEndpoint { @ReadOperation diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support-docker/src/main/java/org/springframework/boot/testsupport/container/TestImage.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support-docker/src/main/java/org/springframework/boot/testsupport/container/TestImage.java index cd59344757..b38c1233ee 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support-docker/src/main/java/org/springframework/boot/testsupport/container/TestImage.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support-docker/src/main/java/org/springframework/boot/testsupport/container/TestImage.java @@ -84,17 +84,6 @@ public enum TestImage { CASSANDRA("cassandra", "3.11.10", () -> CassandraContainer.class, (container) -> ((CassandraContainer) container).withStartupTimeout(Duration.ofMinutes(10))), - /** - * A container image suitable for testing Cassandra using the deprecated - * {@link org.testcontainers.containers.CassandraContainer}. - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of {@link #CASSANDRA} - */ - @SuppressWarnings("deprecation") - @Deprecated(since = "3.4.0", forRemoval = true) - CASSANDRA_DEPRECATED("cassandra", "3.11.10", () -> org.testcontainers.containers.CassandraContainer.class, - (container) -> ((org.testcontainers.containers.CassandraContainer) container) - .withStartupTimeout(Duration.ofMinutes(10))), - /** * A container image suitable for testing ClickHouse. */ @@ -136,16 +125,6 @@ public enum TestImage { */ CONFLUENT_KAFKA("confluentinc/cp-kafka", "7.4.0", () -> ConfluentKafkaContainer.class), - /** - * A container image suitable for testing Confluent's distribution of Kafka using the - * deprecated {@link org.testcontainers.containers.KafkaContainer}. - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of {@link #CONFLUENT_KAFKA} - */ - @SuppressWarnings("deprecation") - @Deprecated(since = "3.4.0", forRemoval = true) - CONFLUENT_KAFKA_DEPRECATED("confluentinc/cp-kafka", "7.4.0", - () -> org.testcontainers.containers.KafkaContainer.class), - /** * A container image suitable for testing LLDAP. */ diff --git a/spring-boot-project/spring-boot-tracing/src/main/java/org/springframework/boot/tracing/autoconfigure/otlp/OtlpTracingConnectionDetails.java b/spring-boot-project/spring-boot-tracing/src/main/java/org/springframework/boot/tracing/autoconfigure/otlp/OtlpTracingConnectionDetails.java index 238d3082f9..338fcae1da 100644 --- a/spring-boot-project/spring-boot-tracing/src/main/java/org/springframework/boot/tracing/autoconfigure/otlp/OtlpTracingConnectionDetails.java +++ b/spring-boot-project/spring-boot-tracing/src/main/java/org/springframework/boot/tracing/autoconfigure/otlp/OtlpTracingConnectionDetails.java @@ -27,16 +27,6 @@ import org.springframework.boot.autoconfigure.service.connection.ConnectionDetai */ public interface OtlpTracingConnectionDetails extends ConnectionDetails { - /** - * Address to where tracing will be published. - * @return the address to where tracing will be published - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of {@link #getUrl(Transport)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - default String getUrl() { - return getUrl(Transport.HTTP); - } - /** * Address to where tracing will be published. * @param transport the transport to use diff --git a/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowServerProperties.java b/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowServerProperties.java index 77c6084351..a7b11de3b5 100644 --- a/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowServerProperties.java +++ b/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowServerProperties.java @@ -26,7 +26,6 @@ import java.util.Map; import io.undertow.UndertowOptions; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; import org.springframework.util.unit.DataSize; /** @@ -101,14 +100,6 @@ public class UndertowServerProperties { */ private int maxCookies = 200; - /** - * Whether the server should decode percent encoded slash characters. Enabling encoded - * slashes can have security implications due to different servers interpreting the - * slash differently. Only enable this if you have a legacy application that requires - * it. Has no effect when server.undertow.decode-slash is set. - */ - private boolean allowEncodedSlash = false; - /** * Whether encoded slash characters (%2F) should be decoded. Decoding can cause * security problems if a front-end proxy does not perform the same decoding. Only @@ -210,17 +201,6 @@ public class UndertowServerProperties { this.maxCookies = maxCookies; } - @DeprecatedConfigurationProperty(replacement = "server.undertow.decode-slash", since = "3.0.3") - @Deprecated(forRemoval = true, since = "3.0.3") - public boolean isAllowEncodedSlash() { - return this.allowEncodedSlash; - } - - @Deprecated(forRemoval = true, since = "3.0.3") - public void setAllowEncodedSlash(boolean allowEncodedSlash) { - this.allowEncodedSlash = allowEncodedSlash; - } - public Boolean getDecodeSlash() { return this.decodeSlash; } diff --git a/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizer.java b/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizer.java index 7ea9d8f41c..55f7a79a20 100644 --- a/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizer.java +++ b/spring-boot-project/spring-boot-undertow/src/main/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizer.java @@ -106,7 +106,7 @@ public class UndertowWebServerFactoryCustomizer map.from(this.undertowProperties::getMaxParameters).to(serverOptions.option(UndertowOptions.MAX_PARAMETERS)); map.from(this.undertowProperties::getMaxHeaders).to(serverOptions.option(UndertowOptions.MAX_HEADERS)); map.from(this.undertowProperties::getMaxCookies).to(serverOptions.option(UndertowOptions.MAX_COOKIES)); - mapSlashProperties(this.undertowProperties, serverOptions); + mapSlashProperty(this.undertowProperties, serverOptions); map.from(this.undertowProperties::isDecodeUrl).to(serverOptions.option(UndertowOptions.DECODE_URL)); map.from(this.undertowProperties::getUrlCharset) .as(Charset::name) @@ -121,10 +121,8 @@ public class UndertowWebServerFactoryCustomizer map.from(this.undertowProperties.getOptions()::getSocket).to(socketOptions.forEach(socketOptions::option)); } - @SuppressWarnings({ "deprecation", "removal" }) - private void mapSlashProperties(UndertowServerProperties properties, ServerOptions serverOptions) { + private void mapSlashProperty(UndertowServerProperties properties, ServerOptions serverOptions) { PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull(); - map.from(properties::isAllowEncodedSlash).to(serverOptions.option(UndertowOptions.ALLOW_ENCODED_SLASH)); map.from(properties::getDecodeSlash).to(serverOptions.option(UndertowOptions.DECODE_SLASH)); } diff --git a/spring-boot-project/spring-boot-undertow/src/test/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizerTests.java b/spring-boot-project/spring-boot-undertow/src/test/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizerTests.java index cf0dcf1c24..16ed9ff588 100644 --- a/spring-boot-project/spring-boot-undertow/src/test/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizerTests.java +++ b/spring-boot-project/spring-boot-undertow/src/test/java/org/springframework/boot/undertow/autoconfigure/UndertowWebServerFactoryCustomizerTests.java @@ -150,13 +150,6 @@ class UndertowWebServerFactoryCustomizerTests { then(factory).should().setWorkerThreads(10); } - @Test - @Deprecated(forRemoval = true, since = "3.0.3") - void allowEncodedSlashes() { - bind("server.undertow.allow-encoded-slash=true"); - assertThat(boundServerOption(UndertowOptions.ALLOW_ENCODED_SLASH)).isTrue(); - } - @Test void enableSlashDecoding() { bind("server.undertow.decode-slash=true"); diff --git a/spring-boot-project/spring-boot-web-server-test/src/main/java/org/springframework/boot/web/server/test/client/TestRestTemplate.java b/spring-boot-project/spring-boot-web-server-test/src/main/java/org/springframework/boot/web/server/test/client/TestRestTemplate.java index 3423bdf94e..983e699cc0 100644 --- a/spring-boot-project/spring-boot-web-server-test/src/main/java/org/springframework/boot/web/server/test/client/TestRestTemplate.java +++ b/spring-boot-project/spring-boot-web-server-test/src/main/java/org/springframework/boot/web/server/test/client/TestRestTemplate.java @@ -21,28 +21,18 @@ import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; -import java.time.Duration; import java.util.Map; import java.util.Set; -import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.UnaryOperator; import javax.net.ssl.SSLContext; -import org.apache.hc.client5.http.classic.HttpClient; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.cookie.StandardCookieSpec; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.client5.http.impl.classic.HttpClients; -import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; -import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; -import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy; import org.apache.hc.client5.http.ssl.TlsSocketStrategy; -import org.apache.hc.core5.http.io.SocketConfig; -import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.http.ssl.TLS; import org.apache.hc.core5.ssl.SSLContextBuilder; import org.apache.hc.core5.ssl.TrustStrategy; @@ -61,7 +51,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.RequestEntity.UriTemplateRequestEntity; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.web.client.NoOpResponseErrorHandler; @@ -162,9 +151,6 @@ public class TestRestTemplate { if (requestFactoryBuilder instanceof HttpComponentsClientHttpRequestFactoryBuilder) { builder = builder.requestFactoryBuilder(applyHttpClientOptions( (HttpComponentsClientHttpRequestFactoryBuilder) requestFactoryBuilder, httpClientOptions)); - if (HttpClientOption.ENABLE_REDIRECTS.isPresent(httpClientOptions)) { - builder = builder.redirects(HttpRedirects.FOLLOW); - } } if (username != null || password != null) { builder = builder.basicAuthentication(username, password); @@ -1056,14 +1042,6 @@ public class TestRestTemplate { */ ENABLE_COOKIES, - /** - * Enable redirects. - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link TestRestTemplate#withRedirects(HttpRedirects)} - */ - @Deprecated(since = "3.5.0", forRemoval = true) - ENABLE_REDIRECTS, - /** * Use a {@link TlsSocketStrategy} that trusts self-signed certificates. */ @@ -1075,89 +1053,6 @@ public class TestRestTemplate { } - /** - * {@link HttpComponentsClientHttpRequestFactory} to apply customizations. - * - * @deprecated since 3.5.0 for removal in 4.0.0 - */ - @Deprecated(since = "3.5.0", forRemoval = true) - protected static class CustomHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory { - - private final String cookieSpec; - - private final boolean enableRedirects; - - /** - * Create a new {@link CustomHttpComponentsClientHttpRequestFactory} instance. - * @param httpClientOptions the {@link HttpClient} options - * @param settings the settings to apply - */ - public CustomHttpComponentsClientHttpRequestFactory(HttpClientOption[] httpClientOptions, - ClientHttpRequestFactorySettings settings) { - this.cookieSpec = (HttpClientOption.ENABLE_COOKIES.isPresent(httpClientOptions) ? StandardCookieSpec.STRICT - : StandardCookieSpec.IGNORE); - this.enableRedirects = settings.redirects() != HttpRedirects.DONT_FOLLOW; - boolean ssl = HttpClientOption.SSL.isPresent(httpClientOptions); - if (settings.readTimeout() != null || ssl) { - setHttpClient(createHttpClient(settings.readTimeout(), ssl)); - } - if (settings.connectTimeout() != null) { - setConnectTimeout((int) settings.connectTimeout().toMillis()); - } - } - - private HttpClient createHttpClient(Duration readTimeout, boolean ssl) { - try { - HttpClientBuilder builder = HttpClients.custom(); - builder.setConnectionManager(createConnectionManager(readTimeout, ssl)); - builder.setDefaultRequestConfig(createRequestConfig()); - return builder.build(); - } - catch (Exception ex) { - throw new IllegalStateException("Unable to create customized HttpClient", ex); - } - } - - private PoolingHttpClientConnectionManager createConnectionManager(Duration readTimeout, boolean ssl) - throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { - PoolingHttpClientConnectionManagerBuilder builder = PoolingHttpClientConnectionManagerBuilder.create(); - if (ssl) { - builder.setTlsSocketStrategy(createTlsSocketStrategy()); - } - if (readTimeout != null) { - SocketConfig socketConfig = SocketConfig.custom() - .setSoTimeout((int) readTimeout.toMillis(), TimeUnit.MILLISECONDS) - .build(); - builder.setDefaultSocketConfig(socketConfig); - } - return builder.build(); - } - - private TlsSocketStrategy createTlsSocketStrategy() - throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { - SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) - .build(); - return new DefaultClientTlsStrategy(sslContext, new String[] { TLS.V_1_3.getId(), TLS.V_1_2.getId() }, null, - null, null); - } - - @Override - protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { - HttpClientContext context = HttpClientContext.create(); - context.setRequestConfig(createRequestConfig()); - return context; - } - - protected RequestConfig createRequestConfig() { - RequestConfig.Builder builder = RequestConfig.custom(); - builder.setCookieSpec(this.cookieSpec); - builder.setAuthenticationEnabled(false); - builder.setRedirectsEnabled(this.enableRedirects); - return builder.build(); - } - - } - /** * Factory used to create a {@link TlsSocketStrategy} supporting self-signed * certificates. diff --git a/spring-boot-project/spring-boot-web-server-test/src/test/java/org/springframework/boot/web/server/test/client/TestRestTemplateTests.java b/spring-boot-project/spring-boot-web-server-test/src/test/java/org/springframework/boot/web/server/test/client/TestRestTemplateTests.java index a837291feb..a773f6cc3f 100644 --- a/spring-boot-project/spring-boot-web-server-test/src/test/java/org/springframework/boot/web/server/test/client/TestRestTemplateTests.java +++ b/spring-boot-project/spring-boot-web-server-test/src/test/java/org/springframework/boot/web/server/test/client/TestRestTemplateTests.java @@ -140,11 +140,8 @@ class TestRestTemplateTests { } @Test - @SuppressWarnings("removal") void options() { - RequestConfig config = getRequestConfig( - new TestRestTemplate(HttpClientOption.ENABLE_REDIRECTS, HttpClientOption.ENABLE_COOKIES)); - assertThat(config.isRedirectsEnabled()).isTrue(); + RequestConfig config = getRequestConfig(new TestRestTemplate(HttpClientOption.ENABLE_COOKIES)); assertThat(config.getCookieSpec()).isEqualTo("strict"); } @@ -164,13 +161,9 @@ class TestRestTemplateTests { RestTemplateBuilder builder = new RestTemplateBuilder() .requestFactoryBuilder(ClientHttpRequestFactoryBuilder.httpComponents()); assertThat(getRedirectStrategy((RestTemplateBuilder) null)).matches(this::isFollowStrategy); - assertThat(getRedirectStrategy(null, HttpClientOption.ENABLE_REDIRECTS)).matches(this::isFollowStrategy); assertThat(getRedirectStrategy(builder)).matches(this::isFollowStrategy); - assertThat(getRedirectStrategy(builder, HttpClientOption.ENABLE_REDIRECTS)).matches(this::isFollowStrategy); assertThat(getRedirectStrategy(builder.redirects(HttpRedirects.DONT_FOLLOW))) .matches(this::isDontFollowStrategy); - assertThat(getRedirectStrategy(builder.redirects(HttpRedirects.DONT_FOLLOW), HttpClientOption.ENABLE_REDIRECTS)) - .matches(this::isFollowStrategy); } @Test diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java index c4902fc8c0..3b176860c1 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ResourceBanner.java @@ -138,10 +138,7 @@ public class ResourceBanner implements Banner { } private Map getVersionsMap(Class sourceClass, Environment environment, String defaultValue) { - String appVersion = getApplicationVersion(sourceClass); - if (appVersion == null) { - appVersion = getApplicationVersion(environment); - } + String appVersion = getApplicationVersion(environment); String bootVersion = getBootVersion(); Map versions = new HashMap<>(); versions.put("application.version", getVersionString(appVersion, false, defaultValue)); @@ -151,17 +148,6 @@ public class ResourceBanner implements Banner { return versions; } - /** - * Returns the application version. - * @param sourceClass the source class - * @return the application version or {@code null} if unknown - * @deprecated since 3.4.0 for removal in 4.0.0 - */ - @Deprecated(since = "3.4.0", forRemoval = true) - protected String getApplicationVersion(Class sourceClass) { - return null; - } - private String getApplicationVersion(Environment environment) { return environment.getProperty("spring.application.version"); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java index 427009c37a..86ca1d313d 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java @@ -381,7 +381,6 @@ public class SpringApplication { listeners.contextPrepared(context); bootstrapContext.close(context); if (this.properties.isLogStartupInfo()) { - logStartupInfo(context.getParent() == null); logStartupInfo(context); logStartupProfileInfo(context); } @@ -623,17 +622,6 @@ public class SpringApplication { } } - /** - * Called to log startup information, subclasses may override to add additional - * logging. - * @param isRoot true if this application is the root of a context hierarchy - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #logStartupInfo(ConfigurableApplicationContext)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - protected void logStartupInfo(boolean isRoot) { - } - /** * Called to log active profile information. * @param context the application context diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java index 7e413a9a5a..da7ed69a32 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/annotation/Configurations.java @@ -73,9 +73,8 @@ public abstract class Configurations { */ protected Configurations(Collection> classes) { Assert.notNull(classes, "'classes' must not be null"); - Collection> sorted = sort(classes); this.sorter = null; - this.classes = Collections.unmodifiableSet(new LinkedHashSet<>(sorted)); + this.classes = Collections.unmodifiableSet(new LinkedHashSet<>(classes)); this.beanNameGenerator = null; } @@ -99,18 +98,6 @@ public abstract class Configurations { return this.classes; } - /** - * Sort configuration classes into the order that they should be applied. - * @param classes the classes to sort - * @return a sorted set of classes - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link #Configurations(UnaryOperator, Collection, Function)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - protected Collection> sort(Collection> classes) { - return classes; - } - /** * Merge configurations from another source of the same type. * @param other the other {@link Configurations} (must be of the same type as this diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/io/ApplicationResourceLoader.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/io/ApplicationResourceLoader.java index a99e660534..7d135ef2dc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/io/ApplicationResourceLoader.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/io/ApplicationResourceLoader.java @@ -50,29 +50,6 @@ import org.springframework.util.StringUtils; */ public class ApplicationResourceLoader extends DefaultResourceLoader { - /** - * Create a new {@code ApplicationResourceLoader}. - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of {@link #get()} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public ApplicationResourceLoader() { - this(null); - } - - /** - * Create a new {@code ApplicationResourceLoader}. - * @param classLoader the {@link ClassLoader} to load class path resources with, or - * {@code null} for using the thread context class loader at the time of actual - * resource access - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of {@link #get(ClassLoader)} - */ - @Deprecated(since = "3.4.0", forRemoval = true) - public ApplicationResourceLoader(ClassLoader classLoader) { - super(classLoader); - SpringFactoriesLoader loader = SpringFactoriesLoader.forDefaultResourceLocation(classLoader); - getProtocolResolvers().addAll(loader.load(ProtocolResolver.class)); - } - @Override protected Resource getResourceByPath(String path) { return new ApplicationResource(path); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java index 13c8794493..bff76170cf 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java @@ -122,14 +122,11 @@ public class LoggingSystemProperties { } protected void apply(LogFile logFile, PropertyResolver resolver) { - Charset defaultCharset = getDefaultCharset(); - Charset consoleCharset = (defaultCharset != null) ? defaultCharset : getDefaultConsoleCharset(); - Charset fileCharset = (defaultCharset != null) ? defaultCharset : getDefaultFileCharset(); setSystemProperty(LoggingSystemProperty.APPLICATION_NAME, resolver); setSystemProperty(LoggingSystemProperty.APPLICATION_GROUP, resolver); setSystemProperty(LoggingSystemProperty.PID, new ApplicationPid().toString()); - setSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET, resolver, consoleCharset.name()); - setSystemProperty(LoggingSystemProperty.FILE_CHARSET, resolver, fileCharset.name()); + setSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET, resolver, getDefaultConsoleCharset().name()); + setSystemProperty(LoggingSystemProperty.FILE_CHARSET, resolver, getDefaultFileCharset().name()); setSystemProperty(LoggingSystemProperty.CONSOLE_THRESHOLD, resolver, this::thresholdMapper); setSystemProperty(LoggingSystemProperty.FILE_THRESHOLD, resolver, this::thresholdMapper); setSystemProperty(LoggingSystemProperty.EXCEPTION_CONVERSION_WORD, resolver); @@ -145,17 +142,6 @@ public class LoggingSystemProperties { } } - /** - * Returns the default charset. - * @return the default charset - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of - * {@link #getDefaultConsoleCharset()} and {@link #getDefaultFileCharset()}. - */ - @Deprecated(since = "3.5.0", forRemoval = true) - protected Charset getDefaultCharset() { - return null; - } - /** * Returns the default console charset. * @return the default console charset diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/ApplicationNameConverter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/ApplicationNameConverter.java deleted file mode 100644 index 282e983d45..0000000000 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/ApplicationNameConverter.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.logging.logback; - -import ch.qos.logback.classic.pattern.ClassicConverter; -import ch.qos.logback.classic.pattern.PropertyConverter; -import ch.qos.logback.classic.spi.ILoggingEvent; - -import org.springframework.boot.logging.LoggingSystemProperty; - -/** - * Logback {@link ClassicConverter} to convert the - * {@link LoggingSystemProperty#APPLICATION_NAME APPLICATION_NAME} into a value suitable - * for logging. Similar to Logback's {@link PropertyConverter} but a non-existent property - * is logged as an empty string rather than {@code null}. - * - * @author Andy Wilkinson - * @author Phillip Webb - * @since 3.2.4 - * @deprecated since 3.4.0 for removal in 4.0.0 in favor of - * {@link EnclosedInSquareBracketsConverter} - */ -@Deprecated(since = "3.4.0", forRemoval = true) -public class ApplicationNameConverter extends ClassicConverter { - - private static final String ENVIRONMENT_VARIABLE_NAME = LoggingSystemProperty.APPLICATION_NAME - .getEnvironmentVariableName(); - - @Override - public String convert(ILoggingEvent event) { - String applicationName = event.getLoggerContextVO().getPropertyMap().get(ENVIRONMENT_VARIABLE_NAME); - applicationName = (applicationName != null) ? applicationName : System.getProperty(ENVIRONMENT_VARIABLE_NAME); - return (applicationName != null) ? applicationName : ""; - } - -} diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java index 6be56b1dd7..a490713a0a 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/DefaultLogbackConfiguration.java @@ -98,7 +98,6 @@ class DefaultLogbackConfiguration { } private void defaults(LogbackConfigurator config) { - deprecatedDefaults(config); config.conversionRule("clr", ColorConverter.class, ColorConverter::new); config.conversionRule("correlationId", CorrelationIdConverter.class, CorrelationIdConverter::new); config.conversionRule("esb", EnclosedInSquareBracketsConverter.class, EnclosedInSquareBracketsConverter::new); @@ -123,11 +122,6 @@ class DefaultLogbackConfiguration { config.logger("org.springframework.boot.actuate.endpoint.jmx", Level.WARN); } - @SuppressWarnings("removal") - private void deprecatedDefaults(LogbackConfigurator config) { - config.conversionRule("applicationName", ApplicationNameConverter.class, ApplicationNameConverter::new); - } - void putProperty(LogbackConfigurator config, String name, String val) { config.getContext().putProperty(name, resolve(config, val)); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackRuntimeHints.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackRuntimeHints.java index 072dbf94a9..cb5a3c79cc 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackRuntimeHints.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackRuntimeHints.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2024 the original author or authors. + * Copyright 2012-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,6 @@ class LogbackRuntimeHints implements RuntimeHintsRegistrar { registerHintsForLogbackLoggingSystemTypeChecks(reflection, classLoader); registerHintsForBuiltInLogbackConverters(reflection); registerHintsForSpringBootConverters(reflection); - registerHintsForDeprecateSpringBootConverters(reflection); } private void registerHintsForLogbackLoggingSystemTypeChecks(ReflectionHints reflection, ClassLoader classLoader) { @@ -64,11 +63,6 @@ class LogbackRuntimeHints implements RuntimeHintsRegistrar { WhitespaceThrowableProxyConverter.class, CorrelationIdConverter.class); } - @SuppressWarnings("removal") - private void registerHintsForDeprecateSpringBootConverters(ReflectionHints reflection) { - registerForPublicConstructorInvocation(reflection, ApplicationNameConverter.class); - } - private void registerForPublicConstructorInvocation(ReflectionHints reflection, Class... classes) { reflection.registerTypes(TypeReference.listOf(classes), (hint) -> hint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)); diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerBuilder.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerBuilder.java index 8573e9b6ae..c0f34d32b7 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerBuilder.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerBuilder.java @@ -57,25 +57,6 @@ public class ThreadPoolTaskSchedulerBuilder { this(null, null, null, null, null, null); } - /** - * Constructs a new {@code ThreadPoolTaskSchedulerBuilder} instance with the specified - * configuration. - * @param poolSize the maximum allowed number of threads - * @param awaitTermination whether the executor should wait for scheduled tasks to - * complete on shutdown - * @param awaitTerminationPeriod the maximum time the executor is supposed to block on - * shutdown - * @param threadNamePrefix the prefix to use for the names of newly created threads - * @param taskSchedulerCustomizers the customizers to apply to the - * {@link ThreadPoolTaskScheduler} - * @deprecated since 3.5.0 for removal in 4.0.0 in favor of the default constructor - */ - @Deprecated(since = "3.5.0", forRemoval = true) - public ThreadPoolTaskSchedulerBuilder(Integer poolSize, Boolean awaitTermination, Duration awaitTerminationPeriod, - String threadNamePrefix, Set taskSchedulerCustomizers) { - this(poolSize, awaitTermination, awaitTerminationPeriod, threadNamePrefix, null, taskSchedulerCustomizers); - } - private ThreadPoolTaskSchedulerBuilder(Integer poolSize, Boolean awaitTermination, Duration awaitTerminationPeriod, String threadNamePrefix, TaskDecorator taskDecorator, Set taskSchedulerCustomizers) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java index 7143492552..dc175d7472 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java @@ -21,7 +21,6 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; @@ -50,27 +49,6 @@ class ConfigurationsTests { .withMessageContaining("'classes' must not be null"); } - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void createShouldSortClassesUsingSortMethod() { - TestDeprecatedSortedConfigurations configurations = new TestDeprecatedSortedConfigurations( - Arrays.asList(OutputStream.class, InputStream.class)); - assertThat(configurations.getClasses()).containsExactly(InputStream.class, OutputStream.class); - } - - @Test - @Deprecated(since = "3.4.0", forRemoval = true) - void getClassesShouldMergeByClassAndSortUsingSortMethod() { - Configurations c1 = new TestDeprecatedSortedConfigurations( - Arrays.asList(OutputStream.class, InputStream.class)); - Configurations c2 = new TestConfigurations(Collections.singletonList(Short.class)); - Configurations c3 = new TestDeprecatedSortedConfigurations(Arrays.asList(String.class, Integer.class)); - Configurations c4 = new TestConfigurations(Arrays.asList(Long.class, Byte.class)); - Class[] classes = Configurations.getClasses(c1, c2, c3, c4); - assertThat(classes).containsExactly(Short.class, Long.class, Byte.class, InputStream.class, Integer.class, - OutputStream.class, String.class); - } - @Test void createShouldSortClasses() { TestConfigurations configurations = new TestConfigurations(Sorter.instance, OutputStream.class, @@ -146,26 +124,6 @@ class ConfigurationsTests { } - @Order(Ordered.LOWEST_PRECEDENCE) - @SuppressWarnings("removal") - static class TestDeprecatedSortedConfigurations extends Configurations { - - protected TestDeprecatedSortedConfigurations(Collection> classes) { - super(classes); - } - - @Override - protected Collection> sort(Collection> classes) { - return Sorter.instance.apply(classes); - } - - @Override - protected Configurations merge(Set> mergedClasses) { - return new TestDeprecatedSortedConfigurations(mergedClasses); - } - - } - static class Sorter implements UnaryOperator>> { static final Sorter instance = new Sorter(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ApplicationNameConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ApplicationNameConverterTests.java deleted file mode 100644 index 40507f6d71..0000000000 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/ApplicationNameConverterTests.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.logging.logback; - -import java.util.Collections; - -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.spi.LoggerContextVO; -import ch.qos.logback.classic.spi.LoggingEvent; -import org.junit.jupiter.api.Test; - -import org.springframework.boot.logging.LoggingSystemProperty; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for {@link ApplicationNameConverter}. - * - * @author Andy Wilkinson - */ -@SuppressWarnings({ "deprecation", "removal" }) -class ApplicationNameConverterTests { - - private final ApplicationNameConverter converter; - - private final LoggingEvent event = new LoggingEvent(); - - ApplicationNameConverterTests() { - this.converter = new ApplicationNameConverter(); - this.converter.setContext(new LoggerContext()); - this.event.setLoggerContextRemoteView( - new LoggerContextVO("test", Collections.emptyMap(), System.currentTimeMillis())); - } - - @Test - void whenNoLoggedApplicationNameConvertReturnsEmptyString() { - withLoggedApplicationName(null, () -> { - this.converter.start(); - String converted = this.converter.convert(this.event); - assertThat(converted).isEqualTo(""); - }); - } - - @Test - void whenLoggedApplicationNameConvertReturnsIt() { - withLoggedApplicationName("my-application", () -> { - this.converter.start(); - String converted = this.converter.convert(this.event); - assertThat(converted).isEqualTo("my-application"); - }); - } - - private void withLoggedApplicationName(String name, Runnable action) { - if (name == null) { - System.clearProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName()); - } - else { - System.setProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName(), name); - } - try { - action.run(); - } - finally { - System.clearProperty(LoggingSystemProperty.APPLICATION_NAME.getEnvironmentVariableName()); - } - } - -} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index 8e0f71a07f..f323b28d53 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -301,18 +301,6 @@ class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { assertThat(configuration).isNull(); } - @Test - @Deprecated(since = "3.3.5", forRemoval = true) - void getLoggerConfigurationForALL() { - this.loggingSystem.beforeInitialize(); - initialize(this.initializationContext, null, null); - Logger logger = (Logger) LoggerFactory.getILoggerFactory().getLogger(getClass().getName()); - logger.setLevel(Level.ALL); - LoggerConfiguration configuration = this.loggingSystem.getLoggerConfiguration(getClass().getName()); - assertThat(configuration) - .isEqualTo(new LoggerConfiguration(getClass().getName(), LogLevel.TRACE, LogLevel.TRACE)); - } - @Test void systemLevelTraceShouldReturnNativeLevelTraceNotAll() { this.loggingSystem.beforeInitialize(); diff --git a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SpyBeanSampleDataJpaApplicationTests.java b/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SpyBeanSampleDataJpaApplicationTests.java deleted file mode 100644 index 7d376dff49..0000000000 --- a/spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-data-jpa/src/test/java/smoketest/data/jpa/SpyBeanSampleDataJpaApplicationTests.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2012-2024 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package smoketest.data.jpa; - -import org.junit.jupiter.api.Test; -import smoketest.data.jpa.service.CityRepository; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.test.web.servlet.assertj.MockMvcTester; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.then; - -/** - * Tests for {@link SampleDataJpaApplication} that use {@link SpyBean @SpyBean}. - * - * @author Andy Wilkinson - * @deprecated since 3.4.0 for removal in 4.0.0 - */ -@SuppressWarnings("removal") -@Deprecated(since = "3.4.0", forRemoval = true) -@SpringBootTest -@AutoConfigureMockMvc -@AutoConfigureTestDatabase -class SpyBeanSampleDataJpaApplicationTests { - - @Autowired - private MockMvcTester mvc; - - @SpyBean - private CityRepository repository; - - @Test - void testHome() { - assertThat(this.mvc.get().uri("/")).hasStatusOk().hasBodyTextEqualTo("Bath"); - then(this.repository).should().findByNameAndCountryAllIgnoringCase("Bath", "UK"); - } - -}