From ca262eaa1c21fa367783def51c33657abf78f99c Mon Sep 17 00:00:00 2001 From: Spring Buildmaster Date: Wed, 14 Jul 2021 06:48:14 +0000 Subject: [PATCH 001/140] Next development version (v5.3.10-SNAPSHOT) --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index c05ae8cc9dd2..28b12e96c3a3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -version=5.3.9-SNAPSHOT +version=5.3.10-SNAPSHOT org.gradle.jvmargs=-Xmx1536M org.gradle.caching=true org.gradle.parallel=true From 0b1d14cdd95eb7582d19daa9f31c13b8f8bfb86d Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 16 Jul 2021 09:34:12 +0100 Subject: [PATCH 002/140] Follow-up fix, checking also "ws" and port 80 case See gh-27097 --- .../web/util/UriComponentsBuilder.java | 3 ++- .../web/util/UriComponentsBuilderTests.java | 23 ++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java index 6787571c4c97..d378a36840a0 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java @@ -881,7 +881,8 @@ else if (isForwardedSslOn(headers)) { "with the removeOnly=true. Request headers: " + headers); } - if (this.scheme != null && ((this.scheme.equals("http") && "80".equals(this.port)) || + if (this.scheme != null && + (((this.scheme.equals("http") || this.scheme.equals("ws")) && "80".equals(this.port)) || ((this.scheme.equals("https") || this.scheme.equals("wss")) && "443".equals(this.port)))) { port(null); } diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index 52623dacc9af..d6d971c4ed5a 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java @@ -378,7 +378,7 @@ void fromHttpRequest() { @ParameterizedTest // gh-17368, gh-27097 @ValueSource(strings = {"https", "wss"}) - void fromHttpRequestResetsPortBeforeSettingIt(String protocol) { + void fromHttpRequestResetsPort443(String protocol) { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("X-Forwarded-Proto", protocol); request.addHeader("X-Forwarded-Host", "84.198.58.199"); @@ -397,6 +397,27 @@ void fromHttpRequestResetsPortBeforeSettingIt(String protocol) { assertThat(result.getPath()).isEqualTo("/rest/mobile/users/1"); } + @ParameterizedTest // gh-27097 + @ValueSource(strings = {"http", "ws"}) + void fromHttpRequestResetsPort80(String protocol) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("X-Forwarded-Proto", protocol); + request.addHeader("X-Forwarded-Host", "84.198.58.199"); + request.addHeader("X-Forwarded-Port", 80); + request.setScheme("http"); + request.setServerName("example.com"); + request.setServerPort(80); + request.setRequestURI("/path"); + + HttpRequest httpRequest = new ServletServerHttpRequest(request); + UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); + + assertThat(result.getScheme()).isEqualTo(protocol); + assertThat(result.getHost()).isEqualTo("84.198.58.199"); + assertThat(result.getPort()).isEqualTo(-1); + assertThat(result.getPath()).isEqualTo("/path"); + } + @Test // SPR-14761 void fromHttpRequestWithForwardedIPv4Host() { MockHttpServletRequest request = new MockHttpServletRequest(); From e0c0e7f878df0d0e0c5a8ebb615f22527390d72e Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sat, 17 Jul 2021 17:03:51 +0300 Subject: [PATCH 003/140] Fix typo in ref docs --- src/docs/asciidoc/web/webmvc.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/docs/asciidoc/web/webmvc.adoc b/src/docs/asciidoc/web/webmvc.adoc index 2133ce377f86..077bcf39cc56 100644 --- a/src/docs/asciidoc/web/webmvc.adoc +++ b/src/docs/asciidoc/web/webmvc.adoc @@ -5386,7 +5386,7 @@ You can configure how Spring MVC determines the requested media types from the r By default, only the `Accept` header is checked. -If you must use URL-based content type resolution, consider using the query parameten +If you must use URL-based content type resolution, consider using the query parameter strategy over path extensions. See <> and <> for more details. From 9c0825629b715949b7082201bbcd90bfbf9d660b Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sat, 17 Jul 2021 17:53:43 +0300 Subject: [PATCH 004/140] Reintroduce left-hand side navigation in ref docs A side effect of 71995a90876fd5b0aa39259df35476fcc3b0c5ef caused the dynamic table of contents in the left-hand side navigation to no longer be displayed, likely due to the missing "details" DIV. This commit addresses this issue by applying the custom header only to index.adoc. Consequently, the TOC is now displayed again on all pages except the index page, but the customized header is no longer applied to those pages. We may revisit this issue if we decide that we want the custom header on all pages (and not just the index page). Closes gh-27177 --- gradle/docs.gradle | 5 +---- .../{docinfo-header.html => index-docinfo-header.html} | 5 +++++ src/docs/asciidoc/index.adoc | 1 + 3 files changed, 7 insertions(+), 4 deletions(-) rename src/docs/asciidoc/{docinfo-header.html => index-docinfo-header.html} (57%) diff --git a/gradle/docs.gradle b/gradle/docs.gradle index 085d291e0742..4b6e139b6513 100644 --- a/gradle/docs.gradle +++ b/gradle/docs.gradle @@ -139,7 +139,7 @@ asciidoctorj { icons: 'font', idprefix: '', idseparator: '-', - docinfo: 'shared', + docinfo: 'shared,private-header', // https://docs.asciidoctor.org/asciidoctor/latest/docinfo/ revnumber: project.version, sectanchors: '', sectnums: '', @@ -163,9 +163,6 @@ asciidoctorj { asciidoctor { baseDirFollowsSourceDir() configurations 'asciidoctorExt' - attributes([ - noheader: '' // custom header in docinfo-header.html - ]) sources { include '*.adoc' } diff --git a/src/docs/asciidoc/docinfo-header.html b/src/docs/asciidoc/index-docinfo-header.html similarity index 57% rename from src/docs/asciidoc/docinfo-header.html rename to src/docs/asciidoc/index-docinfo-header.html index 1be13e03b75b..485f2e4e9803 100644 --- a/src/docs/asciidoc/docinfo-header.html +++ b/src/docs/asciidoc/index-docinfo-header.html @@ -1,4 +1,9 @@ diff --git a/src/docs/asciidoc/index.adoc b/src/docs/asciidoc/index.adoc index 3df3d0d55ef1..69a81c4c2611 100644 --- a/src/docs/asciidoc/index.adoc +++ b/src/docs/asciidoc/index.adoc @@ -1,3 +1,4 @@ +:noheader: = Spring Framework Documentation [horizontal] From 2594f4e0584269a7dab0e2c37c1d871405548547 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 23 Jul 2021 12:18:15 +0200 Subject: [PATCH 005/140] Avoid unnecessary cause initialization in ResponseStatusException Closes gh-27196 --- .../web/server/ResponseStatusException.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/server/ResponseStatusException.java b/spring-web/src/main/java/org/springframework/web/server/ResponseStatusException.java index 8582e8625cd3..73f41c48c71b 100644 --- a/spring-web/src/main/java/org/springframework/web/server/ResponseStatusException.java +++ b/spring-web/src/main/java/org/springframework/web/server/ResponseStatusException.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -47,7 +47,7 @@ public class ResponseStatusException extends NestedRuntimeException { * @param status the HTTP status (required) */ public ResponseStatusException(HttpStatus status) { - this(status, null, null); + this(status, null); } /** @@ -57,7 +57,10 @@ public ResponseStatusException(HttpStatus status) { * @param reason the associated reason (optional) */ public ResponseStatusException(HttpStatus status, @Nullable String reason) { - this(status, reason, null); + super(""); + Assert.notNull(status, "HttpStatus is required"); + this.status = status.value(); + this.reason = reason; } /** From ba08006d52a1dace8c6af0b713f63eb75bc9d976 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 23 Jul 2021 12:19:35 +0200 Subject: [PATCH 006/140] ObjectMapper.configure(MapperFeature, boolean) is deprecated as of Jackson 2.13 Closes gh-27206 --- .../jms/support/converter/MappingJackson2MessageConverter.java | 3 ++- .../messaging/converter/MappingJackson2MessageConverter.java | 3 ++- .../http/converter/json/Jackson2ObjectMapperBuilder.java | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/spring-jms/src/main/java/org/springframework/jms/support/converter/MappingJackson2MessageConverter.java b/spring-jms/src/main/java/org/springframework/jms/support/converter/MappingJackson2MessageConverter.java index 819bbdb3f800..401f5c0cb5ed 100644 --- a/spring-jms/src/main/java/org/springframework/jms/support/converter/MappingJackson2MessageConverter.java +++ b/spring-jms/src/main/java/org/springframework/jms/support/converter/MappingJackson2MessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -92,6 +92,7 @@ public class MappingJackson2MessageConverter implements SmartMessageConverter, B private ClassLoader beanClassLoader; + @SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean) public MappingJackson2MessageConverter() { this.objectMapper = new ObjectMapper(); this.objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); diff --git a/spring-messaging/src/main/java/org/springframework/messaging/converter/MappingJackson2MessageConverter.java b/spring-messaging/src/main/java/org/springframework/messaging/converter/MappingJackson2MessageConverter.java index 349b07ad19db..9bb32eebd942 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/converter/MappingJackson2MessageConverter.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/converter/MappingJackson2MessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -88,6 +88,7 @@ public MappingJackson2MessageConverter(MimeType... supportedMimeTypes) { } + @SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean) private ObjectMapper initObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); diff --git a/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java b/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java index 39cf383cb3a3..0157d4efb61d 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java +++ b/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -796,6 +796,7 @@ private void addDeserializers(SimpleModule module) { module.addDeserializer((Class) type, (JsonDeserializer) deserializer)); } + @SuppressWarnings("deprecation") // on Jackson 2.13: configure(MapperFeature, boolean) private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) { if (feature instanceof JsonParser.Feature) { objectMapper.configure((JsonParser.Feature) feature, enabled); From af67764edbb90495f492124275dd67e3fe55a146 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 23 Jul 2021 12:20:10 +0200 Subject: [PATCH 007/140] Upgrade to Netty 4.1.66 and Undertow 2.2.9 --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index cd5d270ca119..85555c9e06f1 100644 --- a/build.gradle +++ b/build.gradle @@ -28,7 +28,7 @@ configure(allprojects) { project -> dependencyManagement { imports { mavenBom "com.fasterxml.jackson:jackson-bom:2.12.4" - mavenBom "io.netty:netty-bom:4.1.65.Final" + mavenBom "io.netty:netty-bom:4.1.66.Final" mavenBom "io.projectreactor:reactor-bom:2020.0.9" mavenBom "io.r2dbc:r2dbc-bom:Arabba-SR10" mavenBom "io.rsocket:rsocket-bom:1.1.1" @@ -138,7 +138,7 @@ configure(allprojects) { project -> entry 'tomcat-embed-core' entry 'tomcat-embed-websocket' } - dependencySet(group: 'io.undertow', version: '2.2.8.Final') { + dependencySet(group: 'io.undertow', version: '2.2.9.Final') { entry 'undertow-core' entry('undertow-websockets-jsr') { exclude group: "org.jboss.spec.javax.websocket", name: "jboss-websocket-api_1.1_spec" From 460947651ae4c58d31386a0a14396c273b287119 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Thu, 22 Jul 2021 21:53:14 +0100 Subject: [PATCH 008/140] Minor refactoring in DefaultPathContainer Closes gh-27204 --- .../springframework/http/server/DefaultPathContainer.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/server/DefaultPathContainer.java b/spring-web/src/main/java/org/springframework/http/server/DefaultPathContainer.java index 7d4571dfb88c..e3cadabe9786 100644 --- a/spring-web/src/main/java/org/springframework/http/server/DefaultPathContainer.java +++ b/spring-web/src/main/java/org/springframework/http/server/DefaultPathContainer.java @@ -165,10 +165,10 @@ private static void parsePathParamValues(String input, Charset charset, MultiVal int index = input.indexOf('='); if (index != -1) { String name = input.substring(0, index); - String value = input.substring(index + 1); - for (String v : StringUtils.commaDelimitedListToStringArray(value)) { - name = StringUtils.uriDecode(name, charset); - if (StringUtils.hasText(name)) { + name = StringUtils.uriDecode(name, charset); + if (StringUtils.hasText(name)) { + String value = input.substring(index + 1); + for (String v : StringUtils.commaDelimitedListToStringArray(value)) { output.add(name, StringUtils.uriDecode(v, charset)); } } From d034a1f26d0ea3782f53b8ff7a2a0cea7c825b71 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 23 Jul 2021 17:01:28 +0100 Subject: [PATCH 009/140] Blockhound rule for MediaTypeFactory static initializer Closes gh-26631 --- .../web/server/adapter/WebHttpHandlerBuilder.java | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-web/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerBuilder.java b/spring-web/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerBuilder.java index a73e682a9f73..7222138f44c4 100644 --- a/spring-web/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerBuilder.java +++ b/spring-web/src/main/java/org/springframework/web/server/adapter/WebHttpHandlerBuilder.java @@ -433,6 +433,7 @@ public void applyTo(BlockHound.Builder builder) { // Avoid hard references potentially anywhere in spring-web (no need for structural dependency) + builder.allowBlockingCallsInside("org.springframework.http.MediaTypeFactory", ""); builder.allowBlockingCallsInside("org.springframework.web.util.HtmlUtils", ""); } } From e94811f1b9a616db44ffbab7fbc816589332c6cc Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sat, 24 Jul 2021 21:45:31 +0300 Subject: [PATCH 010/140] Polish WebSocketMessageBrokerConfigurationSupportTests --- ...essageBrokerConfigurationSupportTests.java | 110 ++++++++---------- 1 file changed, 50 insertions(+), 60 deletions(-) diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupportTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupportTests.java index e4ea206c0ebc..fe61f0b8ba12 100644 --- a/spring-websocket/src/test/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupportTests.java +++ b/spring-websocket/src/test/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -47,14 +47,12 @@ import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.stereotype.Controller; -import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.config.WebSocketMessageBrokerStats; import org.springframework.web.socket.handler.TestWebSocketSession; import org.springframework.web.socket.handler.WebSocketHandlerDecorator; -import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory; import org.springframework.web.socket.messaging.StompSubProtocolHandler; import org.springframework.web.socket.messaging.StompTextMessageBuilder; import org.springframework.web.socket.messaging.SubProtocolHandler; @@ -65,29 +63,29 @@ import static org.mockito.Mockito.mock; /** - * Test fixture for {@link WebSocketMessageBrokerConfigurationSupport}. + * Tests for {@link WebSocketMessageBrokerConfigurationSupport}. * * @author Rossen Stoyanchev * @author Sebastien Deleuze */ -public class WebSocketMessageBrokerConfigurationSupportTests { +class WebSocketMessageBrokerConfigurationSupportTests { @Test - public void handlerMapping() { - ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); - SimpleUrlHandlerMapping hm = (SimpleUrlHandlerMapping) config.getBean(HandlerMapping.class); + void handlerMapping() { + ApplicationContext context = createContext(TestChannelConfig.class, TestConfigurer.class); + SimpleUrlHandlerMapping hm = context.getBean(SimpleUrlHandlerMapping.class); assertThat(hm.getOrder()).isEqualTo(1); Map handlerMap = hm.getHandlerMap(); - assertThat(handlerMap.size()).isEqualTo(1); + assertThat(handlerMap).hasSize(1); assertThat(handlerMap.get("/simpleBroker")).isNotNull(); } @Test - public void clientInboundChannelSendMessage() throws Exception { - ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); - TestChannel channel = config.getBean("clientInboundChannel", TestChannel.class); - SubProtocolWebSocketHandler webSocketHandler = config.getBean(SubProtocolWebSocketHandler.class); + void clientInboundChannelSendMessage() throws Exception { + ApplicationContext context = createContext(TestChannelConfig.class, TestConfigurer.class); + TestChannel channel = context.getBean("clientInboundChannel", TestChannel.class); + SubProtocolWebSocketHandler webSocketHandler = context.getBean(SubProtocolWebSocketHandler.class); List interceptors = channel.getInterceptors(); assertThat(interceptors.get(interceptors.size() - 1).getClass()).isEqualTo(ImmutableMessageChannelInterceptor.class); @@ -108,66 +106,66 @@ public void clientInboundChannelSendMessage() throws Exception { } @Test - public void clientOutboundChannel() { - ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); - TestChannel channel = config.getBean("clientOutboundChannel", TestChannel.class); + void clientOutboundChannel() { + ApplicationContext context = createContext(TestChannelConfig.class, TestConfigurer.class); + TestChannel channel = context.getBean("clientOutboundChannel", TestChannel.class); Set handlers = channel.getSubscribers(); List interceptors = channel.getInterceptors(); assertThat(interceptors.get(interceptors.size() - 1).getClass()).isEqualTo(ImmutableMessageChannelInterceptor.class); - assertThat(handlers.size()).isEqualTo(1); - assertThat(handlers.contains(config.getBean(SubProtocolWebSocketHandler.class))).isTrue(); + assertThat(handlers).hasSize(1); + assertThat(handlers).contains(context.getBean(SubProtocolWebSocketHandler.class)); } @Test - public void brokerChannel() { - ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); - TestChannel channel = config.getBean("brokerChannel", TestChannel.class); + void brokerChannel() { + ApplicationContext context = createContext(TestChannelConfig.class, TestConfigurer.class); + TestChannel channel = context.getBean("brokerChannel", TestChannel.class); Set handlers = channel.getSubscribers(); List interceptors = channel.getInterceptors(); assertThat(interceptors.get(interceptors.size() - 1).getClass()).isEqualTo(ImmutableMessageChannelInterceptor.class); - assertThat(handlers.size()).isEqualTo(2); - assertThat(handlers.contains(config.getBean(SimpleBrokerMessageHandler.class))).isTrue(); - assertThat(handlers.contains(config.getBean(UserDestinationMessageHandler.class))).isTrue(); + assertThat(handlers).hasSize(2); + assertThat(handlers).contains(context.getBean(SimpleBrokerMessageHandler.class)); + assertThat(handlers).contains(context.getBean(UserDestinationMessageHandler.class)); } @Test - public void webSocketHandler() { - ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); - SubProtocolWebSocketHandler subWsHandler = config.getBean(SubProtocolWebSocketHandler.class); + void webSocketHandler() { + ApplicationContext context = createContext(TestChannelConfig.class, TestConfigurer.class); + SubProtocolWebSocketHandler subWsHandler = context.getBean(SubProtocolWebSocketHandler.class); - assertThat(subWsHandler.getSendBufferSizeLimit()).isEqualTo((1024 * 1024)); - assertThat(subWsHandler.getSendTimeLimit()).isEqualTo((25 * 1000)); - assertThat(subWsHandler.getTimeToFirstMessage()).isEqualTo((30 * 1000)); + assertThat(subWsHandler.getSendBufferSizeLimit()).isEqualTo(1024 * 1024); + assertThat(subWsHandler.getSendTimeLimit()).isEqualTo(25 * 1000); + assertThat(subWsHandler.getTimeToFirstMessage()).isEqualTo(30 * 1000); Map handlerMap = subWsHandler.getProtocolHandlerMap(); StompSubProtocolHandler protocolHandler = (StompSubProtocolHandler) handlerMap.get("v12.stomp"); - assertThat(protocolHandler.getMessageSizeLimit()).isEqualTo((128 * 1024)); + assertThat(protocolHandler.getMessageSizeLimit()).isEqualTo(128 * 1024); } @Test - public void taskScheduler() { - ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); + void taskScheduler() { + ApplicationContext context = createContext(TestChannelConfig.class, TestConfigurer.class); String name = "messageBrokerSockJsTaskScheduler"; - ThreadPoolTaskScheduler taskScheduler = config.getBean(name, ThreadPoolTaskScheduler.class); + ThreadPoolTaskScheduler taskScheduler = context.getBean(name, ThreadPoolTaskScheduler.class); ScheduledThreadPoolExecutor executor = taskScheduler.getScheduledThreadPoolExecutor(); assertThat(executor.getCorePoolSize()).isEqualTo(Runtime.getRuntime().availableProcessors()); assertThat(executor.getRemoveOnCancelPolicy()).isTrue(); - SimpleBrokerMessageHandler handler = config.getBean(SimpleBrokerMessageHandler.class); + SimpleBrokerMessageHandler handler = context.getBean(SimpleBrokerMessageHandler.class); assertThat(handler.getTaskScheduler()).isNotNull(); - assertThat(handler.getHeartbeatValue()).isEqualTo(new long[] {15000, 15000}); + assertThat(handler.getHeartbeatValue()).containsExactly(15000, 15000); } @Test - public void webSocketMessageBrokerStats() { - ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class); + void webSocketMessageBrokerStats() { + ApplicationContext context = createContext(TestChannelConfig.class, TestConfigurer.class); String name = "webSocketMessageBrokerStats"; - WebSocketMessageBrokerStats stats = config.getBean(name, WebSocketMessageBrokerStats.class); + WebSocketMessageBrokerStats stats = context.getBean(name, WebSocketMessageBrokerStats.class); String actual = stats.toString(); String expected = "WebSocketSession\\[0 current WS\\(0\\)-HttpStream\\(0\\)-HttpPoll\\(0\\), " + "0 total, 0 closed abnormally \\(0 connect failure, 0 send limit, 0 transport error\\)], " + @@ -177,16 +175,16 @@ public void webSocketMessageBrokerStats() { "outboundChannel\\[pool size = \\d, active threads = \\d, queued tasks = \\d, completed tasks = \\d], " + "sockJsScheduler\\[pool size = \\d, active threads = \\d, queued tasks = \\d, completed tasks = \\d]"; - assertThat(actual.matches(expected)).as("\nExpected: " + expected.replace("\\", "") + "\n Actual: " + actual).isTrue(); + assertThat(actual).matches(expected); } @Test - public void webSocketHandlerDecorator() throws Exception { - ApplicationContext config = createConfig(WebSocketHandlerDecoratorConfig.class); - WebSocketHandler handler = config.getBean(SubProtocolWebSocketHandler.class); + void webSocketHandlerDecorator() throws Exception { + ApplicationContext context = createContext(WebSocketHandlerDecoratorConfig.class); + WebSocketHandler handler = context.getBean(SubProtocolWebSocketHandler.class); assertThat(handler).isNotNull(); - SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) config.getBean("stompWebSocketHandlerMapping"); + SimpleUrlHandlerMapping mapping = context.getBean("stompWebSocketHandlerMapping", SimpleUrlHandlerMapping.class); WebSocketHttpRequestHandler httpHandler = (WebSocketHttpRequestHandler) mapping.getHandlerMap().get("/test"); handler = httpHandler.getWebSocketHandler(); @@ -196,11 +194,8 @@ public void webSocketHandlerDecorator() throws Exception { } - private ApplicationContext createConfig(Class... configClasses) { - AnnotationConfigApplicationContext config = new AnnotationConfigApplicationContext(); - config.register(configClasses); - config.refresh(); - return config; + private ApplicationContext createContext(Class... configClasses) { + return new AnnotationConfigApplicationContext(configClasses); } @@ -286,17 +281,12 @@ protected void registerStompEndpoints(StompEndpointRegistry registry) { @Override protected void configureWebSocketTransport(WebSocketTransportRegistration registry) { - registry.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() { - @Override - public WebSocketHandlerDecorator decorate(WebSocketHandler handler) { - return new WebSocketHandlerDecorator(handler) { - @Override - public void afterConnectionEstablished(WebSocketSession session) throws Exception { - session.getAttributes().put("decorated", true); - super.afterConnectionEstablished(session); - } - }; - } + registry.addDecoratorFactory(handler -> new WebSocketHandlerDecorator(handler) { + @Override + public void afterConnectionEstablished(WebSocketSession session) throws Exception { + session.getAttributes().put("decorated", true); + super.afterConnectionEstablished(session); + } }); } } From 42edef0bccb75a09523040b9567866281b574629 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sun, 25 Jul 2021 19:00:52 +0200 Subject: [PATCH 011/140] Avoid StringIndexOutOfBoundsException in WebSocketMessageBrokerStats Prior to this commit, if the TaskExecutor configured in WebSocketMessageBrokerStats for the inboundChannelExecutor or outboundChannelExecutor was not a ThreadPoolTaskExecutor, a StringIndexOutOfBoundsException was thrown when attempting to parse the results of invoking toString() on the executor. The reason is that ThreadPoolTaskExecutor delegates to a ThreadPoolExecutor whose toString() implementation generates text containing "pool size = ...", and WebSocketMessageBrokerStats' getExecutorStatsInfo() method relied on the presence of "pool" in the text returned from toString(). This commit fixes this bug by ensuring that the text returned from toString() contains "pool" before parsing the text. If "pool" is not present in the text, getExecutorStatsInfo() now returns "unknown" instead of throwing a StringIndexOutOfBoundsException. Closes gh-27209 --- .../config/WebSocketMessageBrokerStats.java | 41 ++++++--- .../WebSocketMessageBrokerStatsTests.java | 92 +++++++++++++++++++ 2 files changed, 120 insertions(+), 13 deletions(-) create mode 100644 spring-websocket/src/test/java/org/springframework/web/socket/config/WebSocketMessageBrokerStatsTests.java diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java b/spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java index 6ac28d6fedee..16e1b2f51393 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -20,6 +20,7 @@ import java.time.Instant; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; @@ -49,6 +50,7 @@ * the {@link org.springframework.jmx.export.MBeanExporter MBeanExporter}. * * @author Rossen Stoyanchev + * @author Sam Brannen * @since 4.1 */ public class WebSocketMessageBrokerStats { @@ -174,16 +176,14 @@ public String getStompBrokerRelayStatsInfo() { * Get stats about the executor processing incoming messages from WebSocket clients. */ public String getClientInboundExecutorStatsInfo() { - return (this.inboundChannelExecutor != null ? - getExecutorStatsInfo(this.inboundChannelExecutor) : "null"); + return getExecutorStatsInfo(this.inboundChannelExecutor); } /** * Get stats about the executor processing outgoing messages to WebSocket clients. */ public String getClientOutboundExecutorStatsInfo() { - return (this.outboundChannelExecutor != null ? - getExecutorStatsInfo(this.outboundChannelExecutor) : "null"); + return getExecutorStatsInfo(this.outboundChannelExecutor); } /** @@ -197,16 +197,31 @@ public String getSockJsTaskSchedulerStatsInfo() { return getExecutorStatsInfo(((ThreadPoolTaskScheduler) this.sockJsTaskScheduler) .getScheduledThreadPoolExecutor()); } - else { - return "unknown"; - } + return "unknown"; } - private String getExecutorStatsInfo(Executor executor) { - executor = executor instanceof ThreadPoolTaskExecutor ? - ((ThreadPoolTaskExecutor) executor).getThreadPoolExecutor() : executor; - String str = executor.toString(); - return str.substring(str.indexOf("pool"), str.length() - 1); + private String getExecutorStatsInfo(@Nullable Executor executor) { + if (executor == null) { + return "null"; + } + + if (executor instanceof ThreadPoolTaskExecutor) { + executor = ((ThreadPoolTaskExecutor) executor).getThreadPoolExecutor(); + } + + if (executor instanceof ThreadPoolExecutor) { + // It is assumed that the implementation of toString() in ThreadPoolExecutor + // generates text that ends similar to the following: + // pool size = #, active threads = #, queued tasks = #, completed tasks = #] + String str = executor.toString(); + int indexOfPool = str.indexOf("pool"); + if (indexOfPool != -1) { + // (length - 1) omits the trailing "]" + return str.substring(indexOfPool, str.length() - 1); + } + } + + return "unknown"; } @Override diff --git a/spring-websocket/src/test/java/org/springframework/web/socket/config/WebSocketMessageBrokerStatsTests.java b/spring-websocket/src/test/java/org/springframework/web/socket/config/WebSocketMessageBrokerStatsTests.java new file mode 100644 index 000000000000..324dc4942d23 --- /dev/null +++ b/spring-websocket/src/test/java/org/springframework/web/socket/config/WebSocketMessageBrokerStatsTests.java @@ -0,0 +1,92 @@ +/* + * Copyright 2002-2021 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.web.socket.config; + +import org.junit.jupiter.api.Test; + +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +/** + * Unit tests for {@link WebSocketMessageBrokerStats}. + * + * @author Sam Brannen + * @since 5.3.10 + * @see org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupportTests + */ +class WebSocketMessageBrokerStatsTests { + + private final WebSocketMessageBrokerStats stats = new WebSocketMessageBrokerStats(); + + @Test + void nullValues() { + String expected = "WebSocketSession[null], stompSubProtocol[null], stompBrokerRelay[null], " + + "inboundChannel[null], outboundChannel[null], sockJsScheduler[null]"; + assertThat(stats).hasToString(expected); + } + + @Test + void inboundAndOutboundChannelsWithThreadPoolTaskExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.afterPropertiesSet(); + + stats.setInboundChannelExecutor(executor); + stats.setOutboundChannelExecutor(executor); + + assertThat(stats.getClientInboundExecutorStatsInfo()).as("inbound channel stats") + .isEqualTo("pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0"); + assertThat(stats.getClientOutboundExecutorStatsInfo()).as("outbound channel stats") + .isEqualTo("pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0"); + } + + @Test + void inboundAndOutboundChannelsWithMockedTaskExecutor() { + TaskExecutor executor = mock(TaskExecutor.class); + + stats.setInboundChannelExecutor(executor); + stats.setOutboundChannelExecutor(executor); + + assertThat(stats.getClientInboundExecutorStatsInfo()).as("inbound channel stats").isEqualTo("unknown"); + assertThat(stats.getClientOutboundExecutorStatsInfo()).as("outbound channel stats").isEqualTo("unknown"); + } + + @Test + void sockJsTaskSchedulerWithThreadPoolTaskScheduler() { + ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); + scheduler.afterPropertiesSet(); + + stats.setSockJsTaskScheduler(scheduler); + + assertThat(stats.getSockJsTaskSchedulerStatsInfo()) + .isEqualTo("pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0"); + } + + @Test + void sockJsTaskSchedulerWithMockedTaskScheduler() { + TaskScheduler scheduler = mock(TaskScheduler.class); + + stats.setSockJsTaskScheduler(scheduler); + + assertThat(stats.getSockJsTaskSchedulerStatsInfo()).isEqualTo("unknown"); + } + +} From 161c9dc3bd42f2391eaa9f538d4ccad828da1ab0 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 27 Jul 2021 15:05:43 +0200 Subject: [PATCH 012/140] Improve @Cacheable documentation regarding java.util.Optional This commit improves the documentation for @Cacheable to point out that `null` will be stored in the cache for an empty `Optional` return value. Closes gh-27184 --- .../cache/annotation/Cacheable.java | 10 ++++++---- src/docs/asciidoc/integration.adoc | 14 ++++++++------ 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java b/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java index b93cf9373f8b..e1d2700a4c4c 100644 --- a/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java +++ b/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2021 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. @@ -38,9 +38,11 @@ * replace the default one (see {@link #keyGenerator}). * *

If no value is found in the cache for the computed key, the target method - * will be invoked and the returned value stored in the associated cache. Note - * that Java8's {@code Optional} return types are automatically handled and its - * content is stored in the cache if present. + * will be invoked and the returned value will be stored in the associated cache. + * Note that {@link java.util.Optional} return types are unwrapped automatically. + * If an {@code Optional} value is {@linkplain java.util.Optional#isPresent() + * present}, it will be stored in the associated cache. If an {@code Optional} + * value is not present, {@code null} will be stored in the associated cache. * *

This annotation may be used as a meta-annotation to create custom * composed annotations with attribute overrides. diff --git a/src/docs/asciidoc/integration.adoc b/src/docs/asciidoc/integration.adoc index 9e5596052549..15e49e487d23 100644 --- a/src/docs/asciidoc/integration.adoc +++ b/src/docs/asciidoc/integration.adoc @@ -5688,7 +5688,7 @@ method -- if at least one cache is hit, the associated value is returned. NOTE: All the other caches that do not contain the value are also updated, even though the cached method was not actually invoked. -The following example uses `@Cacheable` on the `findBook` method: +The following example uses `@Cacheable` on the `findBook` method with multiple caches: [source,java,indent=0,subs="verbatim,quotes"] ---- @@ -5896,9 +5896,11 @@ want to cache paperback books, as the following example does: <1> Using the `unless` attribute to block hardbacks. -The cache abstraction supports `java.util.Optional`, using its content as the cached value -only if it is present. `#result` always refers to the business entity and never a -supported wrapper, so the previous example can be rewritten as follows: +The cache abstraction supports `java.util.Optional` return types. If an `Optional` value +is _present_, it will be stored in the associated cache. If an `Optional` value is not +present, `null` will be stored in the associated cache. `#result` always refers to the +business entity and never a supported wrapper, so the previous example can be rewritten +as follows: [source,java,indent=0,subs="verbatim,quotes"] ---- @@ -5906,8 +5908,8 @@ supported wrapper, so the previous example can be rewritten as follows: public Optional findBook(String name) ---- -Note that `result` still refers to `Book` and not `Optional`. As it might be `null`, we -should use the safe navigation operator. +Note that `#result` still refers to `Book` and not `Optional`. Since it might be +`null`, we use SpEL's <>. [[cache-spel-context]] ===== Available Caching SpEL Evaluation Context From a747cc3e91ea3b16be3351edf2ed6d536524ee60 Mon Sep 17 00:00:00 2001 From: Moncef AOUDIA Date: Tue, 27 Jul 2021 11:46:24 +0200 Subject: [PATCH 013/140] Fix error message in SynchronossPartHttpMessageReader --- .../http/codec/multipart/SynchronossPartHttpMessageReader.java | 2 +- .../codec/multipart/SynchronossPartHttpMessageReaderTests.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java index e4eedfd99eca..4a77c1b53139 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java @@ -356,7 +356,7 @@ public StreamStorage newStreamStorageForPartBody(Map> heade this.isFilePart = (MultipartUtils.getFileName(headers) != null); this.partSize = 0; if (maxParts > 0 && index > maxParts) { - throw new DecodingException("Too many parts (" + index + " allowed)"); + throw new DecodingException("Too many parts (" + index + "/" + maxParts + " allowed)"); } return this.storageFactory.newStreamStorageForPartBody(headers, index); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java index ba025cbd6b2d..5948be6f5a10 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java @@ -170,7 +170,7 @@ void readTooManyParts() { .isInstanceOf(DecodingException.class) .hasMessageStartingWith("Failure while parsing part[2]"); assertThat(ex.getCause()) - .hasMessage("Too many parts (2 allowed)"); + .hasMessage("Too many parts (2/1 allowed)"); } ); } From 6c68419073b43fb29114a3af4e402c729084ed84 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 27 Jul 2021 17:41:30 +0100 Subject: [PATCH 014/140] Polishing contribution Closes gh-27216 --- .../SynchronossPartHttpMessageReader.java | 2 +- ...SynchronossPartHttpMessageReaderTests.java | 38 ++++++++----------- 2 files changed, 17 insertions(+), 23 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java index 4a77c1b53139..032b787d887b 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReader.java @@ -356,7 +356,7 @@ public StreamStorage newStreamStorageForPartBody(Map> heade this.isFilePart = (MultipartUtils.getFileName(headers) != null); this.partSize = 0; if (maxParts > 0 && index > maxParts) { - throw new DecodingException("Too many parts (" + index + "/" + maxParts + " allowed)"); + throw new DecodingException("Too many parts: Part[" + index + "] but maxParts=" + maxParts); } return this.storageFactory.newStreamStorageForPartBody(headers, index); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java index 5948be6f5a10..10dbdba63a78 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/multipart/SynchronossPartHttpMessageReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -165,37 +165,31 @@ void gh23768() throws IOException { @Test void readTooManyParts() { - testMultipartExceptions(reader -> reader.setMaxParts(1), ex -> { - assertThat(ex) - .isInstanceOf(DecodingException.class) - .hasMessageStartingWith("Failure while parsing part[2]"); - assertThat(ex.getCause()) - .hasMessage("Too many parts (2/1 allowed)"); - } + testMultipartExceptions(reader -> reader.setMaxParts(1), + ex -> assertThat(ex) + .isInstanceOf(DecodingException.class) + .hasMessageStartingWith("Failure while parsing part[2]") + .hasRootCauseMessage("Too many parts: Part[2] but maxParts=1") ); } @Test void readFilePartTooBig() { - testMultipartExceptions(reader -> reader.setMaxDiskUsagePerPart(5), ex -> { - assertThat(ex) - .isInstanceOf(DecodingException.class) - .hasMessageStartingWith("Failure while parsing part[1]"); - assertThat(ex.getCause()) - .hasMessage("Part[1] exceeded the disk usage limit of 5 bytes"); - } + testMultipartExceptions(reader -> reader.setMaxDiskUsagePerPart(5), + ex -> assertThat(ex) + .isInstanceOf(DecodingException.class) + .hasMessageStartingWith("Failure while parsing part[1]") + .hasRootCauseMessage("Part[1] exceeded the disk usage limit of 5 bytes") ); } @Test void readPartHeadersTooBig() { - testMultipartExceptions(reader -> reader.setMaxInMemorySize(1), ex -> { - assertThat(ex) - .isInstanceOf(DecodingException.class) - .hasMessageStartingWith("Failure while parsing part[1]"); - assertThat(ex.getCause()) - .hasMessage("Part[1] exceeded the in-memory limit of 1 bytes"); - } + testMultipartExceptions(reader -> reader.setMaxInMemorySize(1), + ex -> assertThat(ex) + .isInstanceOf(DecodingException.class) + .hasMessageStartingWith("Failure while parsing part[1]") + .hasRootCauseMessage("Part[1] exceeded the in-memory limit of 1 bytes") ); } From 403e04c0b4a79c68b4caf69aabcc9fd0c7bbbd3c Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Wed, 28 Jul 2021 10:47:36 +0200 Subject: [PATCH 015/140] Polish MockHttpServletResponse --- .../mock/web/MockHttpServletResponse.java | 31 +++++++++++++------ .../servlet/MockHttpServletResponse.java | 31 +++++++++++++------ 2 files changed, 44 insertions(+), 18 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index b7b6b9626aa8..4182597f33de 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -83,7 +83,12 @@ public class MockHttpServletResponse implements HttpServletResponse { @Nullable private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; - private boolean charset = false; + /** + * {@code true} if the character encoding has been explicitly set through + * {@link HttpServletResponse} methods or through a {@code charset} parameter + * on the {@code Content-Type}. + */ + private boolean characterEncodingSet = false; private final ByteArrayOutputStream content = new ByteArrayOutputStream(1024); @@ -117,6 +122,11 @@ public class MockHttpServletResponse implements HttpServletResponse { @Nullable private String errorMessage; + + //--------------------------------------------------------------------- + // Properties for MockRequestDispatcher + //--------------------------------------------------------------------- + @Nullable private String forwardedUrl; @@ -158,24 +168,27 @@ public boolean isWriterAccessAllowed() { } /** - * Return whether the character encoding has been set. - *

If {@code false}, {@link #getCharacterEncoding()} will return a default encoding value. + * Determine whether the character encoding has been explicitly set through + * {@link HttpServletResponse} methods or through a {@code charset} parameter + * on the {@code Content-Type}. + *

If {@code false}, {@link #getCharacterEncoding()} will return a default + * encoding value. */ public boolean isCharset() { - return this.charset; + return this.characterEncodingSet; } @Override public void setCharacterEncoding(String characterEncoding) { this.characterEncoding = characterEncoding; - this.charset = true; + this.characterEncodingSet = true; updateContentTypePropertyAndHeader(); } private void updateContentTypePropertyAndHeader() { if (this.contentType != null) { String value = this.contentType; - if (this.charset && !this.contentType.toLowerCase().contains(CHARSET_PREFIX)) { + if (this.characterEncodingSet && !this.contentType.toLowerCase().contains(CHARSET_PREFIX)) { value = value + ';' + CHARSET_PREFIX + this.characterEncoding; this.contentType = value; } @@ -270,7 +283,7 @@ public void setContentType(@Nullable String contentType) { MediaType mediaType = MediaType.parseMediaType(contentType); if (mediaType.getCharset() != null) { this.characterEncoding = mediaType.getCharset().name(); - this.charset = true; + this.characterEncodingSet = true; } } catch (Exception ex) { @@ -278,7 +291,7 @@ public void setContentType(@Nullable String contentType) { int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX); if (charsetIndex != -1) { this.characterEncoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length()); - this.charset = true; + this.characterEncodingSet = true; } } updateContentTypePropertyAndHeader(); @@ -332,7 +345,7 @@ public boolean isCommitted() { public void reset() { resetBuffer(); this.characterEncoding = null; - this.charset = false; + this.characterEncodingSet = false; this.contentLength = 0; this.contentType = null; this.locale = Locale.getDefault(); diff --git a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java index f3215a88b253..e357bc3ce191 100644 --- a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java +++ b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java @@ -83,7 +83,12 @@ public class MockHttpServletResponse implements HttpServletResponse { @Nullable private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; - private boolean charset = false; + /** + * {@code true} if the character encoding has been explicitly set through + * {@link HttpServletResponse} methods or through a {@code charset} parameter + * on the {@code Content-Type}. + */ + private boolean characterEncodingSet = false; private final ByteArrayOutputStream content = new ByteArrayOutputStream(1024); @@ -117,6 +122,11 @@ public class MockHttpServletResponse implements HttpServletResponse { @Nullable private String errorMessage; + + //--------------------------------------------------------------------- + // Properties for MockRequestDispatcher + //--------------------------------------------------------------------- + @Nullable private String forwardedUrl; @@ -158,24 +168,27 @@ public boolean isWriterAccessAllowed() { } /** - * Return whether the character encoding has been set. - *

If {@code false}, {@link #getCharacterEncoding()} will return a default encoding value. + * Determine whether the character encoding has been explicitly set through + * {@link HttpServletResponse} methods or through a {@code charset} parameter + * on the {@code Content-Type}. + *

If {@code false}, {@link #getCharacterEncoding()} will return a default + * encoding value. */ public boolean isCharset() { - return this.charset; + return this.characterEncodingSet; } @Override public void setCharacterEncoding(String characterEncoding) { this.characterEncoding = characterEncoding; - this.charset = true; + this.characterEncodingSet = true; updateContentTypePropertyAndHeader(); } private void updateContentTypePropertyAndHeader() { if (this.contentType != null) { String value = this.contentType; - if (this.charset && !this.contentType.toLowerCase().contains(CHARSET_PREFIX)) { + if (this.characterEncodingSet && !this.contentType.toLowerCase().contains(CHARSET_PREFIX)) { value = value + ';' + CHARSET_PREFIX + this.characterEncoding; this.contentType = value; } @@ -270,7 +283,7 @@ public void setContentType(@Nullable String contentType) { MediaType mediaType = MediaType.parseMediaType(contentType); if (mediaType.getCharset() != null) { this.characterEncoding = mediaType.getCharset().name(); - this.charset = true; + this.characterEncodingSet = true; } } catch (Exception ex) { @@ -278,7 +291,7 @@ public void setContentType(@Nullable String contentType) { int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX); if (charsetIndex != -1) { this.characterEncoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length()); - this.charset = true; + this.characterEncodingSet = true; } } updateContentTypePropertyAndHeader(); @@ -332,7 +345,7 @@ public boolean isCommitted() { public void reset() { resetBuffer(); this.characterEncoding = null; - this.charset = false; + this.characterEncodingSet = false; this.contentLength = 0; this.contentType = null; this.locale = Locale.getDefault(); From c2f91765b401c2976fd802358e6453d0fad0d2fd Mon Sep 17 00:00:00 2001 From: DongHyuk Date: Wed, 28 Jul 2021 22:19:59 +0900 Subject: [PATCH 016/140] Fix typo in Javadoc in AbstractHandlerMapping Closes gh-27218 --- .../web/servlet/handler/AbstractHandlerMapping.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java index 900b7881be90..d3336710f0c4 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java @@ -276,7 +276,7 @@ public void setInterceptors(Object... interceptors) { * determines the {@code CorsConfiguration} to use which is then further * {@link CorsConfiguration#combine(CorsConfiguration) combined} with the * {@code CorsConfiguration} for the selected handler. - *

This is mutually exclusie with + *

This is mutually exclusive with * {@link #setCorsConfigurationSource(CorsConfigurationSource)}. * @since 4.2 * @see #setCorsProcessor(CorsProcessor) @@ -305,7 +305,7 @@ public void setCorsConfigurations(Map corsConfigurati * {@code CorsConfiguration} determined by the source is * {@link CorsConfiguration#combine(CorsConfiguration) combined} with the * {@code CorsConfiguration} for the selected handler. - *

This is mutually exclusie with {@link #setCorsConfigurations(Map)}. + *

This is mutually exclusive with {@link #setCorsConfigurations(Map)}. * @since 5.1 * @see #setCorsProcessor(CorsProcessor) */ From f1b35f15931e1d0e74df3feb9d74ddecedc694f8 Mon Sep 17 00:00:00 2001 From: Mateusz Swiatkowski <6883643+matvs@users.noreply.github.com> Date: Thu, 29 Jul 2021 11:03:26 +0200 Subject: [PATCH 017/140] Fix reference to Optional.isPresent() in ObjectUtils.isEmpty() Closes gh-27223 --- .../src/main/java/org/springframework/util/ObjectUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/src/main/java/org/springframework/util/ObjectUtils.java b/spring-core/src/main/java/org/springframework/util/ObjectUtils.java index 8089a1313e7b..c331a41c1aa8 100644 --- a/spring-core/src/main/java/org/springframework/util/ObjectUtils.java +++ b/spring-core/src/main/java/org/springframework/util/ObjectUtils.java @@ -114,7 +114,7 @@ public static boolean isEmpty(@Nullable Object[] array) { * Determine whether the given object is empty. *

This method supports the following object types. *

    - *
  • {@code Optional}: considered empty if {@link Optional#empty()}
  • + *
  • {@code Optional}: considered empty if not {@link Optional#isPresent()}
  • *
  • {@code Array}: considered empty if its length is zero
  • *
  • {@link CharSequence}: considered empty if its length is zero
  • *
  • {@link Collection}: delegates to {@link Collection#isEmpty()}
  • From 915f1027a571f850c177a0a7da9263ead95599df Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 29 Jul 2021 11:04:59 +0200 Subject: [PATCH 018/140] Update copyright date See gh-27223 --- .../src/main/java/org/springframework/util/ObjectUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/src/main/java/org/springframework/util/ObjectUtils.java b/spring-core/src/main/java/org/springframework/util/ObjectUtils.java index c331a41c1aa8..f5a703c30181 100644 --- a/spring-core/src/main/java/org/springframework/util/ObjectUtils.java +++ b/spring-core/src/main/java/org/springframework/util/ObjectUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. From 96ee8a3bc71815700c5e952d5eaac733415bfeda Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Wed, 28 Jul 2021 16:08:28 +0200 Subject: [PATCH 019/140] Ensure characterEncoding in MockHttpServletResponse is non-null Closes gh-27219 --- .../mock/web/MockHttpServletResponse.java | 44 ++++++++++--------- .../servlet/result/PrintingResultHandler.java | 7 +-- .../web/MockHttpServletResponseTests.java | 4 ++ .../result/PrintingResultHandlerTests.java | 12 +---- .../servlet/MockHttpServletResponse.java | 44 ++++++++++--------- 5 files changed, 53 insertions(+), 58 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index 4182597f33de..a3140793791e 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -80,7 +80,6 @@ public class MockHttpServletResponse implements HttpServletResponse { private boolean writerAccessAllowed = true; - @Nullable private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; /** @@ -171,8 +170,8 @@ public boolean isWriterAccessAllowed() { * Determine whether the character encoding has been explicitly set through * {@link HttpServletResponse} methods or through a {@code charset} parameter * on the {@code Content-Type}. - *

    If {@code false}, {@link #getCharacterEncoding()} will return a default - * encoding value. + *

    If {@code false}, {@link #getCharacterEncoding()} will return the default + * character encoding. */ public boolean isCharset() { return this.characterEncodingSet; @@ -180,16 +179,21 @@ public boolean isCharset() { @Override public void setCharacterEncoding(String characterEncoding) { + setExplicitCharacterEncoding(characterEncoding); + updateContentTypePropertyAndHeader(); + } + + private void setExplicitCharacterEncoding(String characterEncoding) { + Assert.notNull(characterEncoding, "'characterEncoding' must not be null"); this.characterEncoding = characterEncoding; this.characterEncodingSet = true; - updateContentTypePropertyAndHeader(); } private void updateContentTypePropertyAndHeader() { if (this.contentType != null) { String value = this.contentType; - if (this.characterEncodingSet && !this.contentType.toLowerCase().contains(CHARSET_PREFIX)) { - value = value + ';' + CHARSET_PREFIX + this.characterEncoding; + if (this.characterEncodingSet && !value.toLowerCase().contains(CHARSET_PREFIX)) { + value += ';' + CHARSET_PREFIX + getCharacterEncoding(); this.contentType = value; } doAddHeaderValue(HttpHeaders.CONTENT_TYPE, value, true); @@ -197,7 +201,6 @@ private void updateContentTypePropertyAndHeader() { } @Override - @Nullable public String getCharacterEncoding() { return this.characterEncoding; } @@ -212,9 +215,7 @@ public ServletOutputStream getOutputStream() { public PrintWriter getWriter() throws UnsupportedEncodingException { Assert.state(this.writerAccessAllowed, "Writer access not allowed"); if (this.writer == null) { - Writer targetWriter = (this.characterEncoding != null ? - new OutputStreamWriter(this.content, this.characterEncoding) : - new OutputStreamWriter(this.content)); + Writer targetWriter = new OutputStreamWriter(this.content, getCharacterEncoding()); this.writer = new ResponsePrintWriter(targetWriter); } return this.writer; @@ -228,14 +229,16 @@ public byte[] getContentAsByteArray() { * Get the content of the response body as a {@code String}, using the charset * specified for the response by the application, either through * {@link HttpServletResponse} methods or through a charset parameter on the - * {@code Content-Type}. + * {@code Content-Type}. If no charset has been explicitly defined, the default + * character encoding will be used. * @return the content as a {@code String} * @throws UnsupportedEncodingException if the character encoding is not supported * @see #getContentAsString(Charset) + * @see #setCharacterEncoding(String) + * @see #setContentType(String) */ public String getContentAsString() throws UnsupportedEncodingException { - return (this.characterEncoding != null ? - this.content.toString(this.characterEncoding) : this.content.toString()); + return this.content.toString(getCharacterEncoding()); } /** @@ -248,11 +251,12 @@ public String getContentAsString() throws UnsupportedEncodingException { * @throws UnsupportedEncodingException if the character encoding is not supported * @since 5.2 * @see #getContentAsString() + * @see #setCharacterEncoding(String) + * @see #setContentType(String) */ public String getContentAsString(Charset fallbackCharset) throws UnsupportedEncodingException { - return (isCharset() && this.characterEncoding != null ? - this.content.toString(this.characterEncoding) : - this.content.toString(fallbackCharset.name())); + String charsetName = (this.characterEncodingSet ? getCharacterEncoding() : fallbackCharset.name()); + return this.content.toString(charsetName); } @Override @@ -282,16 +286,14 @@ public void setContentType(@Nullable String contentType) { try { MediaType mediaType = MediaType.parseMediaType(contentType); if (mediaType.getCharset() != null) { - this.characterEncoding = mediaType.getCharset().name(); - this.characterEncodingSet = true; + setExplicitCharacterEncoding(mediaType.getCharset().name()); } } catch (Exception ex) { // Try to get charset value anyway int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX); if (charsetIndex != -1) { - this.characterEncoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length()); - this.characterEncodingSet = true; + setExplicitCharacterEncoding(contentType.substring(charsetIndex + CHARSET_PREFIX.length())); } } updateContentTypePropertyAndHeader(); @@ -344,7 +346,7 @@ public boolean isCommitted() { @Override public void reset() { resetBuffer(); - this.characterEncoding = null; + this.characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; this.characterEncodingSet = false; this.contentLength = 0; this.contentType = null; diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java index a358760aa3e2..faaae9806db9 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -248,14 +248,11 @@ protected void printFlashMap(FlashMap flashMap) throws Exception { * Print the response. */ protected void printResponse(MockHttpServletResponse response) throws Exception { - String body = (response.getCharacterEncoding() != null ? - response.getContentAsString() : MISSING_CHARACTER_ENCODING); - this.printer.printValue("Status", response.getStatus()); this.printer.printValue("Error message", response.getErrorMessage()); this.printer.printValue("Headers", getResponseHeaders(response)); this.printer.printValue("Content type", response.getContentType()); - this.printer.printValue("Body", body); + this.printer.printValue("Body", response.getContentAsString()); this.printer.printValue("Forwarded URL", response.getForwardedUrl()); this.printer.printValue("Redirected URL", response.getRedirectedUrl()); printCookies(response.getCookies()); diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java index 1b45d2d36c2a..e8ac11b36b3e 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java @@ -551,6 +551,8 @@ private void assertPrimarySessionCookie(String expectedValue) { @Test // gh-25501 void resetResetsCharset() { + assertThat(response.getContentType()).isNull(); + assertThat(response.getCharacterEncoding()).isEqualTo("ISO-8859-1"); assertThat(response.isCharset()).isFalse(); response.setCharacterEncoding("UTF-8"); assertThat(response.isCharset()).isTrue(); @@ -562,6 +564,8 @@ void resetResetsCharset() { response.reset(); + assertThat(response.getContentType()).isNull(); + assertThat(response.getCharacterEncoding()).isEqualTo("ISO-8859-1"); assertThat(response.isCharset()).isFalse(); // Do not invoke setCharacterEncoding() since that sets the charset flag to true. // response.setCharacterEncoding("UTF-8"); diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java index b97f8d3d1f64..f91c39fda969 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -238,16 +238,6 @@ public void printResponseWithDefaultCharacterEncoding() throws Exception { assertValue("MockHttpServletResponse", "Body", "text"); } - @Test - public void printResponseWithoutCharacterEncoding() throws Exception { - this.response.setCharacterEncoding(null); - this.response.getWriter().print("text"); - - this.handler.handle(this.mvcResult); - - assertValue("MockHttpServletResponse", "Body", ""); - } - @Test public void printHandlerNull() throws Exception { StubMvcResult mvcResult = new StubMvcResult(this.request, null, null, null, null, null, this.response); diff --git a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java index e357bc3ce191..fc294fe2b643 100644 --- a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java +++ b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java @@ -80,7 +80,6 @@ public class MockHttpServletResponse implements HttpServletResponse { private boolean writerAccessAllowed = true; - @Nullable private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; /** @@ -171,8 +170,8 @@ public boolean isWriterAccessAllowed() { * Determine whether the character encoding has been explicitly set through * {@link HttpServletResponse} methods or through a {@code charset} parameter * on the {@code Content-Type}. - *

    If {@code false}, {@link #getCharacterEncoding()} will return a default - * encoding value. + *

    If {@code false}, {@link #getCharacterEncoding()} will return the default + * character encoding. */ public boolean isCharset() { return this.characterEncodingSet; @@ -180,16 +179,21 @@ public boolean isCharset() { @Override public void setCharacterEncoding(String characterEncoding) { + setExplicitCharacterEncoding(characterEncoding); + updateContentTypePropertyAndHeader(); + } + + private void setExplicitCharacterEncoding(String characterEncoding) { + Assert.notNull(characterEncoding, "'characterEncoding' must not be null"); this.characterEncoding = characterEncoding; this.characterEncodingSet = true; - updateContentTypePropertyAndHeader(); } private void updateContentTypePropertyAndHeader() { if (this.contentType != null) { String value = this.contentType; - if (this.characterEncodingSet && !this.contentType.toLowerCase().contains(CHARSET_PREFIX)) { - value = value + ';' + CHARSET_PREFIX + this.characterEncoding; + if (this.characterEncodingSet && !value.toLowerCase().contains(CHARSET_PREFIX)) { + value += ';' + CHARSET_PREFIX + getCharacterEncoding(); this.contentType = value; } doAddHeaderValue(HttpHeaders.CONTENT_TYPE, value, true); @@ -197,7 +201,6 @@ private void updateContentTypePropertyAndHeader() { } @Override - @Nullable public String getCharacterEncoding() { return this.characterEncoding; } @@ -212,9 +215,7 @@ public ServletOutputStream getOutputStream() { public PrintWriter getWriter() throws UnsupportedEncodingException { Assert.state(this.writerAccessAllowed, "Writer access not allowed"); if (this.writer == null) { - Writer targetWriter = (this.characterEncoding != null ? - new OutputStreamWriter(this.content, this.characterEncoding) : - new OutputStreamWriter(this.content)); + Writer targetWriter = new OutputStreamWriter(this.content, getCharacterEncoding()); this.writer = new ResponsePrintWriter(targetWriter); } return this.writer; @@ -228,14 +229,16 @@ public byte[] getContentAsByteArray() { * Get the content of the response body as a {@code String}, using the charset * specified for the response by the application, either through * {@link HttpServletResponse} methods or through a charset parameter on the - * {@code Content-Type}. + * {@code Content-Type}. If no charset has been explicitly defined, the default + * character encoding will be used. * @return the content as a {@code String} * @throws UnsupportedEncodingException if the character encoding is not supported * @see #getContentAsString(Charset) + * @see #setCharacterEncoding(String) + * @see #setContentType(String) */ public String getContentAsString() throws UnsupportedEncodingException { - return (this.characterEncoding != null ? - this.content.toString(this.characterEncoding) : this.content.toString()); + return this.content.toString(getCharacterEncoding()); } /** @@ -248,11 +251,12 @@ public String getContentAsString() throws UnsupportedEncodingException { * @throws UnsupportedEncodingException if the character encoding is not supported * @since 5.2 * @see #getContentAsString() + * @see #setCharacterEncoding(String) + * @see #setContentType(String) */ public String getContentAsString(Charset fallbackCharset) throws UnsupportedEncodingException { - return (isCharset() && this.characterEncoding != null ? - this.content.toString(this.characterEncoding) : - this.content.toString(fallbackCharset.name())); + String charsetName = (this.characterEncodingSet ? getCharacterEncoding() : fallbackCharset.name()); + return this.content.toString(charsetName); } @Override @@ -282,16 +286,14 @@ public void setContentType(@Nullable String contentType) { try { MediaType mediaType = MediaType.parseMediaType(contentType); if (mediaType.getCharset() != null) { - this.characterEncoding = mediaType.getCharset().name(); - this.characterEncodingSet = true; + setExplicitCharacterEncoding(mediaType.getCharset().name()); } } catch (Exception ex) { // Try to get charset value anyway int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX); if (charsetIndex != -1) { - this.characterEncoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length()); - this.characterEncodingSet = true; + setExplicitCharacterEncoding(contentType.substring(charsetIndex + CHARSET_PREFIX.length())); } } updateContentTypePropertyAndHeader(); @@ -344,7 +346,7 @@ public boolean isCommitted() { @Override public void reset() { resetBuffer(); - this.characterEncoding = null; + this.characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; this.characterEncodingSet = false; this.contentLength = 0; this.contentType = null; From 5b3f11c543cefabd4de3a1eb1f8b7ab38e394472 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 29 Jul 2021 14:47:31 +0200 Subject: [PATCH 020/140] Add @Nullable to setLocale in MockHttpServletResponse See gh-26493 --- .../springframework/mock/web/MockHttpServletResponse.java | 5 ++++- .../web/testfixture/servlet/MockHttpServletResponse.java | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index a3140793791e..52a7ab354f7e 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -358,7 +358,10 @@ public void reset() { } @Override - public void setLocale(Locale locale) { + public void setLocale(@Nullable Locale locale) { + // Although the Javadoc for javax.servlet.ServletResponse.setLocale(Locale) does not + // state how a null value for the supplied Locale should be handled, both Tomcat and + // Jetty simply ignore a null value. So we do the same here. if (locale == null) { return; } diff --git a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java index fc294fe2b643..7418a2871609 100644 --- a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java +++ b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java @@ -358,7 +358,10 @@ public void reset() { } @Override - public void setLocale(Locale locale) { + public void setLocale(@Nullable Locale locale) { + // Although the Javadoc for javax.servlet.ServletResponse.setLocale(Locale) does not + // state how a null value for the supplied Locale should be handled, both Tomcat and + // Jetty simply ignore a null value. So we do the same here. if (locale == null) { return; } From f2be4e93203d2949a8e46466f92a1715954b85b5 Mon Sep 17 00:00:00 2001 From: Yanming Zhou Date: Fri, 23 Jul 2021 10:00:23 +0800 Subject: [PATCH 021/140] Use MessageSource for @ExceptionHandler methods Follow-up for commit bb816c123ca86c6f373ee2bd1632f43c117a8f15 See gh-27203 --- .../web/method/HandlerMethod.java | 11 ++++- .../support/InvocableHandlerMethod.java | 9 ++++ .../ExceptionHandlerExceptionResolver.java | 4 +- .../ServletInvocableHandlerMethod.java | 8 ++++ ...xceptionHandlerExceptionResolverTests.java | 43 +++++++++++++++++++ 5 files changed, 72 insertions(+), 3 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java index bbcef56c8bab..90e93fd36427 100644 --- a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java @@ -102,11 +102,20 @@ public class HandlerMethod { * Create an instance from a bean instance and a method. */ public HandlerMethod(Object bean, Method method) { + this(bean, method, null); + } + + + /** + * Variant of {@link #HandlerMethod(Object, Method)} that + * also accepts a {@link MessageSource}. + */ + public HandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { Assert.notNull(bean, "Bean is required"); Assert.notNull(method, "Method is required"); this.bean = bean; this.beanFactory = null; - this.messageSource = null; + this.messageSource = messageSource; this.beanType = ClassUtils.getUserClass(bean); this.method = method; this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); diff --git a/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java index b9c9a69c9553..68d7b94d54d1 100644 --- a/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java @@ -20,6 +20,7 @@ import java.lang.reflect.Method; import java.util.Arrays; +import org.springframework.context.MessageSource; import org.springframework.core.CoroutinesUtils; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.KotlinDetector; @@ -71,6 +72,14 @@ public InvocableHandlerMethod(Object bean, Method method) { super(bean, method); } + /** + * Variant of {@link #InvocableHandlerMethod(Object, Method)} that + * also accepts a {@link MessageSource}. + */ + public InvocableHandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { + super(bean, method, messageSource); + } + /** * Construct a new handler method with the given bean instance, method name and parameters. * @param bean the object bean diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java index bdb29fc15a2b..7be174e7a68b 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java @@ -483,7 +483,7 @@ protected ServletInvocableHandlerMethod getExceptionHandlerMethod( } Method method = resolver.resolveMethod(exception); if (method != null) { - return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method); + return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method, this.applicationContext); } // For advice applicability check below (involving base packages, assignable types // and annotation presence), use target class instead of interface-based proxy. @@ -498,7 +498,7 @@ protected ServletInvocableHandlerMethod getExceptionHandlerMethod( ExceptionHandlerMethodResolver resolver = entry.getValue(); Method method = resolver.resolveMethod(exception); if (method != null) { - return new ServletInvocableHandlerMethod(advice.resolveBean(), method); + return new ServletInvocableHandlerMethod(advice.resolveBean(), method, this.applicationContext); } } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java index 8cbdb10549db..88343c3dbfca 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java @@ -25,6 +25,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.context.MessageSource; import org.springframework.core.KotlinDetector; import org.springframework.core.MethodParameter; import org.springframework.core.ResolvableType; @@ -68,6 +69,13 @@ public class ServletInvocableHandlerMethod extends InvocableHandlerMethod { @Nullable private HandlerMethodReturnValueHandlerComposite returnValueHandlers; + /** + * Variant of {@link #ServletInvocableHandlerMethod(Object, Method)} that + * also accepts a {@link MessageSource}. + */ + public ServletInvocableHandlerMethod(Object handler, Method method, @Nullable MessageSource messageSource) { + super(handler, method, messageSource); + } /** * Creates an instance from the given handler and method. diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java index b3757c556eb4..960935036266 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java @@ -19,7 +19,9 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; +import java.net.SocketTimeoutException; import java.util.Collections; +import java.util.Locale; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -30,8 +32,11 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.MethodParameter; import org.springframework.core.annotation.Order; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; @@ -42,6 +47,7 @@ import org.springframework.web.HttpRequestHandler; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.support.WebApplicationObjectSupport; import org.springframework.web.method.HandlerMethod; @@ -333,6 +339,28 @@ void resolveExceptionWithAssertionErrorAsRootCause() throws Exception { assertThat(this.response.getContentAsString()).isEqualTo(rootCause.toString()); } + @Test //gh-27156 + void resolveExceptionWithReasonResovledByMessageSource() throws Exception { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class); + StaticApplicationContext context = new StaticApplicationContext(ctx); + Locale locale = Locale.ENGLISH; + context.addMessage("gateway.timeout", locale, "Gateway Timeout"); + context.refresh(); + LocaleContextHolder.setLocale(locale); + this.resolver.setApplicationContext(context); + this.resolver.afterPropertiesSet(); + + SocketTimeoutException ex = new SocketTimeoutException(); + HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); + ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); + + assertThat(mav).as("Exception was not handled").isNotNull(); + assertThat(mav.isEmpty()).isTrue(); + assertThat(this.response.getStatus()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT.value()); + assertThat(this.response.getErrorMessage()).isEqualTo("Gateway Timeout"); + assertThat(this.response.getContentAsString()).isEqualTo(""); + } + @Test void resolveExceptionControllerAdviceHandler() throws Exception { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class); @@ -530,6 +558,16 @@ public String handleException(Exception ex) { } } + @RestControllerAdvice + @Order(3) + static class ResponseStatusTestExceptionResolver { + + @ExceptionHandler(SocketTimeoutException.class) + @ResponseStatus(code = HttpStatus.GATEWAY_TIMEOUT, reason = "gateway.timeout") + public void handleException(SocketTimeoutException ex) { + + } + } @Configuration static class MyConfig { @@ -543,6 +581,11 @@ public TestExceptionResolver testExceptionResolver() { public AnotherTestExceptionResolver anotherTestExceptionResolver() { return new AnotherTestExceptionResolver(); } + + @Bean + public ResponseStatusTestExceptionResolver responseStatusTestExceptionResolver() { + return new ResponseStatusTestExceptionResolver(); + } } From 55e17ef30636b58052b8a53322394ec9d91df22e Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Wed, 28 Jul 2021 14:44:48 +0100 Subject: [PATCH 022/140] Polishing contribution Closes gh-27203 --- .../web/method/HandlerMethod.java | 6 +++--- .../support/InvocableHandlerMethod.java | 7 ++++--- .../ServletInvocableHandlerMethod.java | 19 +++++++++++-------- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java index 90e93fd36427..35bf35ac01c5 100644 --- a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java @@ -105,12 +105,12 @@ public HandlerMethod(Object bean, Method method) { this(bean, method, null); } - /** * Variant of {@link #HandlerMethod(Object, Method)} that - * also accepts a {@link MessageSource}. + * also accepts a {@link MessageSource} for use from sub-classes. + * @since 5.3.10 */ - public HandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { + protected HandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { Assert.notNull(bean, "Bean is required"); Assert.notNull(method, "Method is required"); this.bean = bean; diff --git a/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java index 68d7b94d54d1..80f98393f3a3 100644 --- a/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -74,9 +74,10 @@ public InvocableHandlerMethod(Object bean, Method method) { /** * Variant of {@link #InvocableHandlerMethod(Object, Method)} that - * also accepts a {@link MessageSource}. + * also accepts a {@link MessageSource}, for use in sub-classes. + * @since 5.3.10 */ - public InvocableHandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { + protected InvocableHandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { super(bean, method, messageSource); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java index 88343c3dbfca..8b2ba44f3ecb 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -69,13 +69,6 @@ public class ServletInvocableHandlerMethod extends InvocableHandlerMethod { @Nullable private HandlerMethodReturnValueHandlerComposite returnValueHandlers; - /** - * Variant of {@link #ServletInvocableHandlerMethod(Object, Method)} that - * also accepts a {@link MessageSource}. - */ - public ServletInvocableHandlerMethod(Object handler, Method method, @Nullable MessageSource messageSource) { - super(handler, method, messageSource); - } /** * Creates an instance from the given handler and method. @@ -84,6 +77,16 @@ public ServletInvocableHandlerMethod(Object handler, Method method) { super(handler, method); } + /** + * Variant of {@link #ServletInvocableHandlerMethod(Object, Method)} that + * also accepts a {@link MessageSource}, e.g. to resolve + * {@code @ResponseStatus} messages with. + * @since 5.3.10 + */ + public ServletInvocableHandlerMethod(Object handler, Method method, @Nullable MessageSource messageSource) { + super(handler, method, messageSource); + } + /** * Create an instance from a {@code HandlerMethod}. */ From e4b9b1fadb35c4e439acc8931910aaba6e1342e3 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 29 Jul 2021 15:38:51 +0200 Subject: [PATCH 023/140] Introduce setDefaultCharacterEncoding() in MockHttpServletResponse Prior to this commit, it was possible to set the character encoding in MockHttpServletResponse via setCharacterEncoding() or setContentType(); however, those methods append "charset=..." to the Content-Type header which may not be an acceptable side effect. This commit addresses this shortcoming by introducing a new setDefaultCharacterEncoding() in MockHttpServletResponse which allows one to override the previously hard coded value of "ISO-8859-1". In addition, setDefaultCharacterEncoding() does not modify the Content-Type header. The reset() method has also been updated to reset the character encoding to the configured default character encoding. Closes gh-27214 --- .../mock/web/MockHttpServletResponse.java | 36 +++++++++++++++---- .../web/MockHttpServletResponseTests.java | 30 ++++++++++++++++ .../servlet/MockHttpServletResponse.java | 36 +++++++++++++++---- 3 files changed, 90 insertions(+), 12 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index 52a7ab354f7e..a1b3eca3b08d 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -80,7 +80,9 @@ public class MockHttpServletResponse implements HttpServletResponse { private boolean writerAccessAllowed = true; - private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; + private String defaultCharacterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; + + private String characterEncoding = this.defaultCharacterEncoding; /** * {@code true} if the character encoding has been explicitly set through @@ -166,12 +168,33 @@ public boolean isWriterAccessAllowed() { return this.writerAccessAllowed; } + /** + * Set the default character encoding for the response. + *

    If this method is not invoked, {@code ISO-8859-1} will be used as the + * default character encoding. + *

    If the {@linkplain #getCharacterEncoding() character encoding} for the + * response has not already been explicitly set via {@link #setCharacterEncoding(String)} + * or {@link #setContentType(String)}, the character encoding for the response + * will be set to the supplied default character encoding. + * @param characterEncoding the default character encoding + * @since 5.3.10 + * @see #setCharacterEncoding(String) + * @see #setContentType(String) + */ + public void setDefaultCharacterEncoding(String characterEncoding) { + Assert.notNull(characterEncoding, "'characterEncoding' must not be null"); + this.defaultCharacterEncoding = characterEncoding; + if (!this.characterEncodingSet) { + this.characterEncoding = characterEncoding; + } + } + /** * Determine whether the character encoding has been explicitly set through * {@link HttpServletResponse} methods or through a {@code charset} parameter * on the {@code Content-Type}. - *

    If {@code false}, {@link #getCharacterEncoding()} will return the default - * character encoding. + *

    If {@code false}, {@link #getCharacterEncoding()} will return the + * {@linkplain #setDefaultCharacterEncoding(String) default character encoding}. */ public boolean isCharset() { return this.characterEncodingSet; @@ -229,8 +252,9 @@ public byte[] getContentAsByteArray() { * Get the content of the response body as a {@code String}, using the charset * specified for the response by the application, either through * {@link HttpServletResponse} methods or through a charset parameter on the - * {@code Content-Type}. If no charset has been explicitly defined, the default - * character encoding will be used. + * {@code Content-Type}. If no charset has been explicitly defined, the + * {@linkplain #setDefaultCharacterEncoding(String) default character encoding} + * will be used. * @return the content as a {@code String} * @throws UnsupportedEncodingException if the character encoding is not supported * @see #getContentAsString(Charset) @@ -346,7 +370,7 @@ public boolean isCommitted() { @Override public void reset() { resetBuffer(); - this.characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; + this.characterEncoding = this.defaultCharacterEncoding; this.characterEncodingSet = false; this.contentLength = 0; this.contentType = null; diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java index e8ac11b36b3e..fe0f90f7b500 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java @@ -195,6 +195,36 @@ void setCharacterEncodingThenContentType() { assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); } + @Test + void defaultCharacterEncoding() { + assertThat(response.isCharset()).isFalse(); + assertThat(response.getContentType()).isNull(); + assertThat(response.getCharacterEncoding()).isEqualTo("ISO-8859-1"); + + response.setDefaultCharacterEncoding("UTF-8"); + assertThat(response.isCharset()).isFalse(); + assertThat(response.getContentType()).isNull(); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); + + response.setContentType("text/plain;charset=UTF-16"); + assertThat(response.isCharset()).isTrue(); + assertThat(response.getContentType()).isEqualTo("text/plain;charset=UTF-16"); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-16"); + + response.reset(); + assertThat(response.isCharset()).isFalse(); + assertThat(response.getContentType()).isNull(); + assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8"); + + response.setCharacterEncoding("FOXTROT"); + assertThat(response.isCharset()).isTrue(); + assertThat(response.getContentType()).isNull(); + assertThat(response.getCharacterEncoding()).isEqualTo("FOXTROT"); + + response.setDefaultCharacterEncoding("ENIGMA"); + assertThat(response.getCharacterEncoding()).isEqualTo("FOXTROT"); + } + @Test void contentLength() { response.setContentLength(66); diff --git a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java index 7418a2871609..4a343c8344c7 100644 --- a/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java +++ b/spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletResponse.java @@ -80,7 +80,9 @@ public class MockHttpServletResponse implements HttpServletResponse { private boolean writerAccessAllowed = true; - private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; + private String defaultCharacterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; + + private String characterEncoding = this.defaultCharacterEncoding; /** * {@code true} if the character encoding has been explicitly set through @@ -166,12 +168,33 @@ public boolean isWriterAccessAllowed() { return this.writerAccessAllowed; } + /** + * Set the default character encoding for the response. + *

    If this method is not invoked, {@code ISO-8859-1} will be used as the + * default character encoding. + *

    If the {@linkplain #getCharacterEncoding() character encoding} for the + * response has not already been explicitly set via {@link #setCharacterEncoding(String)} + * or {@link #setContentType(String)}, the character encoding for the response + * will be set to the supplied default character encoding. + * @param characterEncoding the default character encoding + * @since 5.3.10 + * @see #setCharacterEncoding(String) + * @see #setContentType(String) + */ + public void setDefaultCharacterEncoding(String characterEncoding) { + Assert.notNull(characterEncoding, "'characterEncoding' must not be null"); + this.defaultCharacterEncoding = characterEncoding; + if (!this.characterEncodingSet) { + this.characterEncoding = characterEncoding; + } + } + /** * Determine whether the character encoding has been explicitly set through * {@link HttpServletResponse} methods or through a {@code charset} parameter * on the {@code Content-Type}. - *

    If {@code false}, {@link #getCharacterEncoding()} will return the default - * character encoding. + *

    If {@code false}, {@link #getCharacterEncoding()} will return the + * {@linkplain #setDefaultCharacterEncoding(String) default character encoding}. */ public boolean isCharset() { return this.characterEncodingSet; @@ -229,8 +252,9 @@ public byte[] getContentAsByteArray() { * Get the content of the response body as a {@code String}, using the charset * specified for the response by the application, either through * {@link HttpServletResponse} methods or through a charset parameter on the - * {@code Content-Type}. If no charset has been explicitly defined, the default - * character encoding will be used. + * {@code Content-Type}. If no charset has been explicitly defined, the + * {@linkplain #setDefaultCharacterEncoding(String) default character encoding} + * will be used. * @return the content as a {@code String} * @throws UnsupportedEncodingException if the character encoding is not supported * @see #getContentAsString(Charset) @@ -346,7 +370,7 @@ public boolean isCommitted() { @Override public void reset() { resetBuffer(); - this.characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; + this.characterEncoding = this.defaultCharacterEncoding; this.characterEncodingSet = false; this.contentLength = 0; this.contentType = null; From 881fa889fcdb1870e12beb7010408a316b30dc62 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 29 Jul 2021 19:18:18 +0200 Subject: [PATCH 024/140] Apply global ResultHandlers before ResultMatchers in MockMvc Prior to this commit, MockMvc applied global ResultMatchers before global ResultHandlers. This lead to unexpected scenarios where a failing matcher would prevent a handler from being applied. One concrete use case is `alwaysDo(print(System.err))` which should print out MockMvc results for debugging purposes. However, if MockMvc is configured with something like `alwaysExpect(content().string("?"))` and the expectation fails, the user will never see the expected debug output to help diagnose the problem. This commit addresses this issue by applying global ResultHandlers before ResultMatchers in MockMvc. Closes gh-27225 --- .../test/web/servlet/MockMvc.java | 8 +- ...PrintingResultHandlerIntegrationTests.java | 95 +++++++++++++++++++ 2 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java index a8565da45b90..39492cbd0a56 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -217,12 +217,12 @@ private MockHttpServletResponse unwrapResponseIfNecessary(ServletResponse servle } private void applyDefaultResultActions(MvcResult mvcResult) throws Exception { - for (ResultMatcher matcher : this.defaultResultMatchers) { - matcher.match(mvcResult); - } for (ResultHandler handler : this.defaultResultHandlers) { handler.handle(mvcResult); } + for (ResultMatcher matcher : this.defaultResultMatchers) { + matcher.match(mvcResult); + } } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java new file mode 100644 index 000000000000..d2a66f5178ba --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java @@ -0,0 +1,95 @@ +/* + * Copyright 2002-2021 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.test.web.servlet.samples.standalone.resulthandlers; + +import java.io.StringWriter; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; + +import org.junit.jupiter.api.Test; + +import org.springframework.test.web.servlet.result.PrintingResultHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; + +/** + * Integration tests for {@link PrintingResultHandler}. + * + * @author Sam Brannen + * @author Rossen Stoyanchev + * @since 5.3.10 + * @see PrintingResultHandlerSmokeTests + * @see org.springframework.test.web.servlet.result.PrintingResultHandlerTests + */ +class PrintingResultHandlerIntegrationTests { + + @Test + void printMvcResultsToWriter() throws Exception { + StringWriter writer = new StringWriter(); + + standaloneSetup(new SimpleController()) + .alwaysDo(print(writer)) + .build() + .perform(get("/").content("Hello Request".getBytes()).characterEncoding("ISO-8859-1")) + .andExpect(content().string("Hello Response")); + + assertThat(writer).asString() + .contains("Hello Request") + .contains("Hello Response") + .contains("Headers = [Set-Cookie:\"enigma=42\", Content-Type:\"text/plain;charset=ISO-8859-1\", Content-Length:\"14\"]"); + } + + @Test + void printMvcResultsToWriterWithFailingGlobalResultMatcher() throws Exception { + StringWriter writer = new StringWriter(); + + try { + standaloneSetup(new SimpleController()) + .alwaysDo(print(writer)) + .alwaysExpect(content().string("Boom!")) + .build() + .perform(get("/").content("Hello Request".getBytes()).characterEncoding("ISO-8859-1")); + } + catch (AssertionError error) { + assertThat(error).hasMessageContaining("Boom!"); + } + + assertThat(writer).asString() + .contains("Hello Request") + .contains("Hello Response") + .contains("Headers = [Set-Cookie:\"enigma=42\", Content-Type:\"text/plain;charset=ISO-8859-1\", Content-Length:\"14\"]"); + } + + + @RestController + private static class SimpleController { + + @GetMapping("/") + String hello(HttpServletResponse response) { + response.addCookie(new Cookie("enigma", "42")); + return "Hello Response"; + } + } + +} From 41fa199178d313bf0399873483d37bb5b298715f Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 29 Jul 2021 19:43:54 +0200 Subject: [PATCH 025/140] Polish PrintingResultHandler --- .../test/web/servlet/result/PrintingResultHandler.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java index faaae9806db9..f0ea1c5b658d 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/PrintingResultHandler.java @@ -123,13 +123,10 @@ protected void printRequest(MockHttpServletRequest request) throws Exception { protected final HttpHeaders getRequestHeaders(MockHttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); - Enumeration names = request.getHeaderNames(); + Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - Enumeration values = request.getHeaders(name); - while (values.hasMoreElements()) { - headers.add(name, values.nextElement()); - } + String name = names.nextElement(); + headers.put(name, Collections.list(request.getHeaders(name))); } return headers; } From 0f421f9f86fc6a06d2b41fbe538ac6b97ed2470f Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 30 Jul 2021 14:42:45 +0200 Subject: [PATCH 026/140] Support default character encoding for response in MockMvc Commit e4b9b1fadb introduced support for setting the default character encoding in MockHttpServletResponse. This commit introduces support for configuring the default character encoding in the underlying MockHttpServletResponse used in MockMvc. Closes gh-27230 --- .../test/web/servlet/MockMvc.java | 16 ++++++++++++++ .../web/servlet/MockMvcBuilderSupport.java | 21 ++++++++++++++++++- .../servlet/setup/AbstractMockMvcBuilder.java | 21 +++++++++++++++++-- .../setup/ConfigurableMockMvcBuilder.java | 18 +++++++++++++++- .../samples/standalone/ResponseBodyTests.java | 16 +++++++------- 5 files changed, 81 insertions(+), 11 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java index 39492cbd0a56..0c8a28c7fd69 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java @@ -16,6 +16,7 @@ package org.springframework.test.web.servlet; +import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @@ -78,6 +79,9 @@ public final class MockMvc { @Nullable private RequestBuilder defaultRequestBuilder; + @Nullable + private Charset defaultResponseCharacterEncoding; + private List defaultResultMatchers = new ArrayList<>(); private List defaultResultHandlers = new ArrayList<>(); @@ -106,6 +110,14 @@ void setDefaultRequest(@Nullable RequestBuilder requestBuilder) { this.defaultRequestBuilder = requestBuilder; } + /** + * The default character encoding to be applied to every response. + * @see org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder#defaultResponseCharacterEncoding(Charset) + */ + void setDefaultResponseCharacterEncoding(@Nullable Charset defaultResponseCharacterEncoding) { + this.defaultResponseCharacterEncoding = defaultResponseCharacterEncoding; + } + /** * Expectations to assert after every performed request. * @see org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder#alwaysExpect(ResultMatcher) @@ -169,6 +181,10 @@ public ResultActions perform(RequestBuilder requestBuilder) throws Exception { servletResponse = mockResponse; } + if (this.defaultResponseCharacterEncoding != null) { + mockResponse.setDefaultCharacterEncoding(this.defaultResponseCharacterEncoding.name()); + } + if (requestBuilder instanceof SmartRequestBuilder) { request = ((SmartRequestBuilder) requestBuilder).postProcessRequest(request); } diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java index d08a96f3227d..d635b00b1bab 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2021 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,6 +16,7 @@ package org.springframework.test.web.servlet; +import java.nio.charset.Charset; import java.util.List; import javax.servlet.Filter; @@ -37,10 +38,28 @@ * @author Rossen Stoyanchev * @author Rob Winch * @author Stephane Nicoll + * @author Sam Brannen * @since 3.2 */ public abstract class MockMvcBuilderSupport { + /** + * Delegates to {@link #createMockMvc(Filter[], MockServletConfig, WebApplicationContext, RequestBuilder, List, List, List)} + * for creation of the {@link MockMvc} instance and configures that instance + * with the supplied {@code defaultResponseCharacterEncoding}. + * @since 5.3.10 + */ + protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig, + WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder, + @Nullable Charset defaultResponseCharacterEncoding, + List globalResultMatchers, List globalResultHandlers, + @Nullable List dispatcherServletCustomizers) { + + MockMvc mockMvc = createMockMvc(filters, servletConfig, webAppContext, defaultRequestBuilder, globalResultMatchers, globalResultHandlers, dispatcherServletCustomizers); + mockMvc.setDefaultResponseCharacterEncoding(defaultResponseCharacterEncoding); + return mockMvc; + } + protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig, WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder, List globalResultMatchers, List globalResultHandlers, diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/setup/AbstractMockMvcBuilder.java b/spring-test/src/main/java/org/springframework/test/web/servlet/setup/AbstractMockMvcBuilder.java index de05563d7043..e5ed43ce30aa 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/setup/AbstractMockMvcBuilder.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/setup/AbstractMockMvcBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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,6 +16,7 @@ package org.springframework.test.web.servlet.setup; +import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @@ -48,6 +49,7 @@ * * @author Rossen Stoyanchev * @author Stephane Nicoll + * @author Sam Brannen * @since 4.0 * @param a self reference to the builder type */ @@ -59,6 +61,9 @@ public abstract class AbstractMockMvcBuilder @Nullable private RequestBuilder defaultRequestBuilder; + @Nullable + private Charset defaultResponseCharacterEncoding; + private final List globalResultMatchers = new ArrayList<>(); private final List globalResultHandlers = new ArrayList<>(); @@ -95,6 +100,17 @@ public final T defaultRequest(RequestBuilder requestBuilder) { return self(); } + /** + * Define the default character encoding to be applied to every response. + * @param defaultResponseCharacterEncoding the default response character encoding + * @since 5.3.10 + */ + @Override + public final T defaultResponseCharacterEncoding(Charset defaultResponseCharacterEncoding) { + this.defaultResponseCharacterEncoding = defaultResponseCharacterEncoding; + return self(); + } + @Override public final T alwaysExpect(ResultMatcher resultMatcher) { this.globalResultMatchers.add(resultMatcher); @@ -157,7 +173,8 @@ public final MockMvc build() { Filter[] filterArray = this.filters.toArray(new Filter[0]); return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder, - this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers); + this.defaultResponseCharacterEncoding, this.globalResultMatchers, this.globalResultHandlers, + this.dispatcherServletCustomizers); } /** diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/setup/ConfigurableMockMvcBuilder.java b/spring-test/src/main/java/org/springframework/test/web/servlet/setup/ConfigurableMockMvcBuilder.java index a619ee7a5882..43ef6ca9547e 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/setup/ConfigurableMockMvcBuilder.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/setup/ConfigurableMockMvcBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,6 +16,8 @@ package org.springframework.test.web.servlet.setup; +import java.nio.charset.Charset; + import javax.servlet.Filter; import org.springframework.test.web.servlet.DispatcherServletCustomizer; @@ -28,6 +30,7 @@ * Defines common methods for building a {@code MockMvc}. * * @author Rossen Stoyanchev + * @author Sam Brannen * @since 4.1 * @param a self reference to the builder type */ @@ -81,6 +84,18 @@ public interface ConfigurableMockMvcBuilder T defaultRequest(RequestBuilder requestBuilder); + /** + * Define the default character encoding to be applied to every response. + *

    The default implementation of this method ignores the supplied value. + * Concrete implementations are therefore encouraged to override this method. + * @param defaultResponseCharacterEncoding the default response character encoding + * @since 5.3.10 + */ + @SuppressWarnings("unchecked") + default T defaultResponseCharacterEncoding(Charset defaultResponseCharacterEncoding) { + return (T) this; + } + /** * Define a global expectation that should always be applied to * every response. For example, status code 200 (OK), content type @@ -110,6 +125,7 @@ public interface ConfigurableMockMvcBuilder T addDispatcherServletCustomizer(DispatcherServletCustomizer customizer); diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java index 2799b24d191e..e6cbe17338e6 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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,8 +16,6 @@ package org.springframework.test.web.servlet.samples.standalone; -import javax.validation.constraints.NotNull; - import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; @@ -25,6 +23,8 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -42,11 +42,14 @@ class ResponseBodyTests { @Test void json() throws Exception { - standaloneSetup(new PersonController()).build() - .perform(get("/person/Lee").accept(MediaType.APPLICATION_JSON)) + standaloneSetup(new PersonController()).defaultResponseCharacterEncoding(UTF_8).build() + // We use a name containing an umlaut to test UTF-8 encoding for the request and the response. + .perform(get("/person/Jürgen").characterEncoding(UTF_8.name()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) - .andExpect(jsonPath("$.name").value("Lee")) + .andExpect(content().encoding(UTF_8.name())) + .andExpect(content().string(containsString("Jürgen"))) + .andExpect(jsonPath("$.name").value("Jürgen")) .andExpect(jsonPath("$.age").value(42)) .andExpect(jsonPath("$.age").value(42.0f)) .andExpect(jsonPath("$.age").value(equalTo(42))) @@ -70,7 +73,6 @@ Person get(@PathVariable String name) { @SuppressWarnings("unused") private static class Person { - @NotNull private final String name; private int age; From 4d115eef91bfb6518d42a5f6fc74d33fbc97bdfa Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 30 Jul 2021 15:20:44 +0200 Subject: [PATCH 027/140] Polishing --- .../MockHttpServletRequestBuilderTests.java | 123 +++++++++--------- .../resultmatchers/ContentAssertionTests.java | 40 +++--- 2 files changed, 73 insertions(+), 90 deletions(-) diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java index 47f51e1046f8..734e24c26fc4 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,7 +32,6 @@ import javax.servlet.ServletContext; import javax.servlet.http.Cookie; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; @@ -58,28 +57,22 @@ * @author Rossen Stoyanchev * @author Sam Brannen */ -public class MockHttpServletRequestBuilderTests { +class MockHttpServletRequestBuilderTests { private final ServletContext servletContext = new MockServletContext(); - private MockHttpServletRequestBuilder builder; - - - @BeforeEach - public void setUp() { - this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo/bar"); - } + private MockHttpServletRequestBuilder builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo/bar"); @Test - public void method() { + void method() { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); assertThat(request.getMethod()).isEqualTo("GET"); } @Test - public void uri() { + void uri() { String uri = "https://java.sun.com:8080/javase/6/docs/api/java/util/BitSet.html?foo=bar#and(java.util.BitSet)"; this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, uri); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -94,7 +87,7 @@ public void uri() { } @Test - public void requestUriWithEncoding() { + void requestUriWithEncoding() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -102,7 +95,7 @@ public void requestUriWithEncoding() { } @Test // SPR-13435 - public void requestUriWithDoubleSlashes() throws URISyntaxException { + void requestUriWithDoubleSlashes() throws URISyntaxException { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, new URI("/test//currentlyValid/0")); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -110,13 +103,13 @@ public void requestUriWithDoubleSlashes() throws URISyntaxException { } @Test // gh-24556 - public void requestUriWithoutScheme() { + void requestUriWithoutScheme() { assertThatIllegalArgumentException().isThrownBy(() -> MockMvcRequestBuilders.get("localhost:8080/path")) .withMessage("'url' should start with a path or be a complete HTTP URL: localhost:8080/path"); } @Test - public void contextPathEmpty() { + void contextPathEmpty() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -126,7 +119,7 @@ public void contextPathEmpty() { } @Test - public void contextPathServletPathEmpty() { + void contextPathServletPathEmpty() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels/42"); this.builder.contextPath("/travel"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -137,7 +130,7 @@ public void contextPathServletPathEmpty() { } @Test - public void contextPathServletPath() { + void contextPathServletPath() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/main/hotels/42"); this.builder.contextPath("/travel"); this.builder.servletPath("/main"); @@ -150,7 +143,7 @@ public void contextPathServletPath() { } @Test - public void contextPathServletPathInfoEmpty() { + void contextPathServletPathInfoEmpty() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels/42"); this.builder.contextPath("/travel"); this.builder.servletPath("/hotels/42"); @@ -162,7 +155,7 @@ public void contextPathServletPathInfoEmpty() { } @Test - public void contextPathServletPathInfo() { + void contextPathServletPathInfo() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/"); this.builder.servletPath("/index.html"); this.builder.pathInfo(null); @@ -174,7 +167,7 @@ public void contextPathServletPathInfo() { } @Test // SPR-16453 - public void pathInfoIsDecoded() { + void pathInfoIsDecoded() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels 42"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -182,7 +175,7 @@ public void pathInfoIsDecoded() { } @Test - public void contextPathServletPathInvalid() { + void contextPathServletPathInvalid() { testContextPathServletPathInvalid("/Foo", "", "Request URI [/foo/bar] does not start with context path [/Foo]"); testContextPathServletPathInvalid("foo", "", "Context path must start with a '/'"); testContextPathServletPathInvalid("/foo/", "", "Context path must not end with a '/'"); @@ -204,7 +197,7 @@ private void testContextPathServletPathInvalid(String contextPath, String servle } @Test - public void requestUriAndFragment() { + void requestUriAndFragment() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo#bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -212,28 +205,28 @@ public void requestUriAndFragment() { } @Test - public void requestParameter() { + void requestParameter() { this.builder.param("foo", "bar", "baz"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Map parameterMap = request.getParameterMap(); - assertThat(parameterMap.get("foo")).isEqualTo(new String[] {"bar", "baz"}); + assertThat(parameterMap.get("foo")).containsExactly("bar", "baz"); } @Test - public void requestParameterFromQuery() { + void requestParameterFromQuery() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo=bar&foo=baz"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Map parameterMap = request.getParameterMap(); - assertThat(parameterMap.get("foo")).isEqualTo(new String[] {"bar", "baz"}); + assertThat(parameterMap.get("foo")).containsExactly("bar", "baz"); assertThat(request.getQueryString()).isEqualTo("foo=bar&foo=baz"); } @Test - public void requestParameterFromQueryList() { + void requestParameterFromQueryList() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo[0]=bar&foo[1]=baz"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -244,19 +237,19 @@ public void requestParameterFromQueryList() { } @Test - public void queryParameter() { + void queryParameter() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/"); this.builder.queryParam("foo", "bar"); this.builder.queryParam("foo", "baz"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertThat(request.getParameterMap().get("foo")).isEqualTo(new String[] {"bar", "baz"}); + assertThat(request.getParameterMap().get("foo")).containsExactly("bar", "baz"); assertThat(request.getQueryString()).isEqualTo("foo=bar&foo=baz"); } @Test - public void queryParameterMap() { + void queryParameterMap() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/"); MultiValueMap queryParams = new LinkedMultiValueMap<>(); List values = new ArrayList<>(); @@ -267,12 +260,12 @@ public void queryParameterMap() { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertThat(request.getParameterMap().get("foo")).isEqualTo(new String[] {"bar", "baz"}); + assertThat(request.getParameterMap().get("foo")).containsExactly("bar", "baz"); assertThat(request.getQueryString()).isEqualTo("foo=bar&foo=baz"); } @Test - public void queryParameterList() { + void queryParameterList() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/"); this.builder.queryParam("foo[0]", "bar"); this.builder.queryParam("foo[1]", "baz"); @@ -285,7 +278,7 @@ public void queryParameterList() { } @Test - public void requestParameterFromQueryWithEncoding() { + void requestParameterFromQueryWithEncoding() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo={value}", "bar=baz"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -295,18 +288,18 @@ public void requestParameterFromQueryWithEncoding() { } @Test // SPR-11043 - public void requestParameterFromQueryNull() { + void requestParameterFromQueryNull() { this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); Map parameterMap = request.getParameterMap(); - assertThat(parameterMap.get("foo")).isEqualTo(new String[] {null}); + assertThat(parameterMap.get("foo")).containsExactly((String) null); assertThat(request.getQueryString()).isEqualTo("foo"); } @Test // SPR-13801 - public void requestParameterFromMultiValueMap() throws Exception { + void requestParameterFromMultiValueMap() throws Exception { MultiValueMap params = new LinkedMultiValueMap<>(); params.add("foo", "bar"); params.add("foo", "baz"); @@ -315,11 +308,11 @@ public void requestParameterFromMultiValueMap() throws Exception { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertThat(request.getParameterMap().get("foo")).isEqualTo(new String[] {"bar", "baz"}); + assertThat(request.getParameterMap().get("foo")).containsExactly("bar", "baz"); } @Test - public void requestParameterFromRequestBodyFormData() throws Exception { + void requestParameterFromRequestBodyFormData() throws Exception { String contentType = "application/x-www-form-urlencoded;charset=UTF-8"; String body = "name+1=value+1&name+2=value+A&name+2=value+B&name+3"; @@ -327,13 +320,13 @@ public void requestParameterFromRequestBodyFormData() throws Exception { .contentType(contentType).content(body.getBytes(StandardCharsets.UTF_8)) .buildRequest(this.servletContext); - assertThat(request.getParameterMap().get("name 1")).isEqualTo(new String[] {"value 1"}); - assertThat(request.getParameterMap().get("name 2")).isEqualTo(new String[] {"value A", "value B"}); - assertThat(request.getParameterMap().get("name 3")).isEqualTo(new String[] {null}); + assertThat(request.getParameterMap().get("name 1")).containsExactly("value 1"); + assertThat(request.getParameterMap().get("name 2")).containsExactly("value A", "value B"); + assertThat(request.getParameterMap().get("name 3")).containsExactly((String) null); } @Test - public void acceptHeader() { + void acceptHeader() { this.builder.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_XML); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -346,14 +339,14 @@ public void acceptHeader() { } @Test // gh-2079 - public void acceptHeaderWithInvalidValues() { + void acceptHeaderWithInvalidValues() { this.builder.accept("any", "any2"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); assertThat(request.getHeader("Accept")).isEqualTo("any, any2"); } @Test - public void contentType() { + void contentType() { this.builder.contentType(MediaType.TEXT_HTML); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -366,7 +359,7 @@ public void contentType() { } @Test - public void contentTypeViaString() { + void contentTypeViaString() { this.builder.contentType("text/html"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -379,14 +372,14 @@ public void contentTypeViaString() { } @Test // gh-2079 - public void contentTypeWithInvalidValue() { + void contentTypeWithInvalidValue() { this.builder.contentType("any"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); assertThat(request.getContentType()).isEqualTo("any"); } @Test // SPR-11308 - public void contentTypeViaHeader() { + void contentTypeViaHeader() { this.builder.header("Content-Type", MediaType.TEXT_HTML_VALUE); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); String contentType = request.getContentType(); @@ -395,14 +388,14 @@ public void contentTypeViaHeader() { } @Test // gh-2079 - public void contentTypeViaHeaderWithInvalidValue() { + void contentTypeViaHeaderWithInvalidValue() { this.builder.header("Content-Type", "yaml"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); assertThat(request.getContentType()).isEqualTo("yaml"); } @Test // SPR-11308 - public void contentTypeViaMultipleHeaderValues() { + void contentTypeViaMultipleHeaderValues() { this.builder.header("Content-Type", MediaType.TEXT_HTML_VALUE, MediaType.ALL_VALUE); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -410,7 +403,7 @@ public void contentTypeViaMultipleHeaderValues() { } @Test - public void body() throws IOException { + void body() throws IOException { byte[] body = "Hello World".getBytes("UTF-8"); this.builder.content(body); @@ -422,7 +415,7 @@ public void body() throws IOException { } @Test - public void header() { + void header() { this.builder.header("foo", "bar", "baz"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -434,7 +427,7 @@ public void header() { } @Test - public void headers() { + void headers() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.put("foo", Arrays.asList("bar", "baz")); @@ -450,7 +443,7 @@ public void headers() { } @Test - public void cookie() { + void cookie() { Cookie cookie1 = new Cookie("foo", "bar"); Cookie cookie2 = new Cookie("baz", "qux"); this.builder.cookie(cookie1, cookie2); @@ -466,13 +459,13 @@ public void cookie() { } @Test - public void noCookies() { + void noCookies() { MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); assertThat(request.getCookies()).isNull(); } @Test - public void locale() { + void locale() { Locale locale = new Locale("nl", "nl"); this.builder.locale(locale); @@ -482,7 +475,7 @@ public void locale() { } @Test - public void characterEncoding() { + void characterEncoding() { String encoding = "UTF-8"; this.builder.characterEncoding(encoding); @@ -492,7 +485,7 @@ public void characterEncoding() { } @Test - public void requestAttribute() { + void requestAttribute() { this.builder.requestAttr("foo", "bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -500,7 +493,7 @@ public void requestAttribute() { } @Test - public void sessionAttribute() { + void sessionAttribute() { this.builder.sessionAttr("foo", "bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -508,7 +501,7 @@ public void sessionAttribute() { } @Test - public void sessionAttributes() { + void sessionAttributes() { Map map = new HashMap<>(); map.put("foo", "bar"); this.builder.sessionAttrs(map); @@ -519,7 +512,7 @@ public void sessionAttributes() { } @Test - public void session() { + void session() { MockHttpSession session = new MockHttpSession(this.servletContext); session.setAttribute("foo", "bar"); this.builder.session(session); @@ -533,7 +526,7 @@ public void session() { } @Test - public void flashAttribute() { + void flashAttribute() { this.builder.flashAttr("foo", "bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -543,7 +536,7 @@ public void flashAttribute() { } @Test - public void principal() { + void principal() { User user = new User(); this.builder.principal(user); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); @@ -552,7 +545,7 @@ public void principal() { } @Test // SPR-12945 - public void mergeInvokesDefaultRequestPostProcessorFirst() { + void mergeInvokesDefaultRequestPostProcessorFirst() { final String ATTR = "ATTR"; final String EXPECTED = "override"; @@ -570,7 +563,7 @@ public void mergeInvokesDefaultRequestPostProcessorFirst() { } @Test // SPR-13719 - public void arbitraryMethod() { + void arbitraryMethod() { String httpMethod = "REPort"; URI url = UriComponentsBuilder.fromPath("/foo/{bar}").buildAndExpand(42).toUri(); this.builder = new MockHttpServletRequestBuilder(httpMethod, url); diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java index 65d0ede06ca9..3b2c8347fa5d 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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,14 +16,12 @@ package org.springframework.test.web.servlet.samples.standalone.resultmatchers; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; -import org.springframework.stereotype.Controller; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -37,6 +35,7 @@ * the character encoding. * * @author Rossen Stoyanchev + * @author Sam Brannen * * @see JsonPathAssertionTests * @see XmlContentAssertionTests @@ -44,15 +43,11 @@ */ public class ContentAssertionTests { - private MockMvc mockMvc; + private final MockMvc mockMvc = standaloneSetup(new SimpleController()).alwaysExpect(status().isOk()).build(); - @BeforeEach - public void setup() { - this.mockMvc = standaloneSetup(new SimpleController()).alwaysExpect(status().isOk()).build(); - } @Test - public void testContentType() throws Exception { + void contentType() throws Exception { this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) .andExpect(content().contentType(MediaType.valueOf("text/plain;charset=ISO-8859-1"))) .andExpect(content().contentType("text/plain;charset=ISO-8859-1")) @@ -67,8 +62,7 @@ public void testContentType() throws Exception { } @Test - public void testContentAsString() throws Exception { - + void contentAsString() throws Exception { this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) .andExpect(content().string("Hello world!")); @@ -81,8 +75,7 @@ public void testContentAsString() throws Exception { } @Test - public void testContentAsBytes() throws Exception { - + void contentAsBytes() throws Exception { this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) .andExpect(content().bytes("Hello world!".getBytes("ISO-8859-1"))); @@ -91,14 +84,13 @@ public void testContentAsBytes() throws Exception { } @Test - public void testContentStringMatcher() throws Exception { + void contentStringMatcher() throws Exception { this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) .andExpect(content().string(containsString("world"))); } @Test - public void testCharacterEncoding() throws Exception { - + void characterEncoding() throws Exception { this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) .andExpect(content().encoding("ISO-8859-1")) .andExpect(content().string(containsString("world"))); @@ -109,18 +101,16 @@ public void testCharacterEncoding() throws Exception { } - @Controller + @RestController private static class SimpleController { - @RequestMapping(value="/handle", produces="text/plain") - @ResponseBody - public String handle() { + @GetMapping(path="/handle", produces="text/plain") + String handle() { return "Hello world!"; } - @RequestMapping(value="/handleUtf8", produces="text/plain;charset=UTF-8") - @ResponseBody - public String handleWithCharset() { + @GetMapping(path="/handleUtf8", produces="text/plain;charset=UTF-8") + String handleWithCharset() { return "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01"; // "Hello world! (Japanese) } } From bd1f5bd9fcd04874fec2c791add3616e9a69b9ce Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 30 Jul 2021 15:24:47 +0200 Subject: [PATCH 028/140] Support Charset for character encoding in MockMvc To improve the developer experience and avoid the use of String literals, this commit provides overloaded support via Charset for character encoding in MockHttpServletRequestBuilder and ContentResultMatchers. Closes gh-27231 --- .../request/MockHttpServletRequestBuilder.java | 14 +++++++++++++- .../web/servlet/result/ContentResultMatchers.java | 14 +++++++++++++- .../MockHttpServletRequestBuilderTests.java | 7 +++++-- .../samples/standalone/ResponseBodyTests.java | 4 ++-- .../resultmatchers/ContentAssertionTests.java | 10 ++++++++++ 5 files changed, 43 insertions(+), 6 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java b/spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java index 7a73e731f5e0..c4ec1cd91733 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -20,6 +20,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.Principal; import java.util.ArrayList; @@ -243,6 +244,17 @@ public MockHttpServletRequestBuilder secure(boolean secure){ return this; } + /** + * Set the character encoding of the request. + * @param encoding the character encoding + * @since 5.3.10 + * @see StandardCharsets + * @see #characterEncoding(String) + */ + public MockHttpServletRequestBuilder characterEncoding(Charset encoding) { + return this.characterEncoding(encoding.name()); + } + /** * Set the character encoding of the request. * @param encoding the character encoding diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java index 87232ae45bc6..f2d9360107f1 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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,6 +16,7 @@ package org.springframework.test.web.servlet.result; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -43,6 +44,7 @@ * {@link MockMvcResultMatchers#content}. * * @author Rossen Stoyanchev + * @author Sam Brannen * @since 3.2 */ public class ContentResultMatchers { @@ -107,6 +109,16 @@ public ResultMatcher contentTypeCompatibleWith(MediaType contentType) { }; } + /** + * Assert the character encoding in the ServletResponse. + * @since 5.3.10 + * @see StandardCharsets + * @see #encoding(String) + */ + public ResultMatcher encoding(Charset characterEncoding) { + return encoding(characterEncoding.name()); + } + /** * Assert the character encoding in the ServletResponse. * @see HttpServletResponse#getCharacterEncoding() diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java index 734e24c26fc4..b493cbbca4d0 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java @@ -477,11 +477,14 @@ void locale() { @Test void characterEncoding() { String encoding = "UTF-8"; - this.builder.characterEncoding(encoding); + this.builder.characterEncoding(encoding); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); - assertThat(request.getCharacterEncoding()).isEqualTo(encoding); + + this.builder.characterEncoding(StandardCharsets.ISO_8859_1); + request = this.builder.buildRequest(this.servletContext); + assertThat(request.getCharacterEncoding()).isEqualTo(StandardCharsets.ISO_8859_1.name()); } @Test diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java index e6cbe17338e6..26b90936dfdc 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ResponseBodyTests.java @@ -44,10 +44,10 @@ class ResponseBodyTests { void json() throws Exception { standaloneSetup(new PersonController()).defaultResponseCharacterEncoding(UTF_8).build() // We use a name containing an umlaut to test UTF-8 encoding for the request and the response. - .perform(get("/person/Jürgen").characterEncoding(UTF_8.name()).accept(MediaType.APPLICATION_JSON)) + .perform(get("/person/Jürgen").characterEncoding(UTF_8).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) - .andExpect(content().encoding(UTF_8.name())) + .andExpect(content().encoding(UTF_8)) .andExpect(content().string(containsString("Jürgen"))) .andExpect(jsonPath("$.name").value("Jürgen")) .andExpect(jsonPath("$.age").value(42)) diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java index 3b2c8347fa5d..2efc51e4afb5 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java @@ -16,6 +16,8 @@ package org.springframework.test.web.servlet.samples.standalone.resultmatchers; +import java.nio.charset.StandardCharsets; + import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; @@ -95,9 +97,17 @@ void characterEncoding() throws Exception { .andExpect(content().encoding("ISO-8859-1")) .andExpect(content().string(containsString("world"))); + this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) + .andExpect(content().encoding(StandardCharsets.ISO_8859_1)) + .andExpect(content().string(containsString("world"))); + this.mockMvc.perform(get("/handleUtf8")) .andExpect(content().encoding("UTF-8")) .andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8"))); + + this.mockMvc.perform(get("/handleUtf8")) + .andExpect(content().encoding(StandardCharsets.UTF_8)) + .andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8"))); } From 01c8de0111806d8f9346f332b22ece9dd9fef618 Mon Sep 17 00:00:00 2001 From: Anton Lyxell Date: Sat, 31 Jul 2021 16:27:43 +0200 Subject: [PATCH 029/140] Simplify getInternalBeanFactoryForBean This commit simplifies getInternalBeanFactoryForBean() in AbstractBeanFactoryBasedTargetSourceCreator via Map::computeIfAbsent. Closes gh-27234 --- .../AbstractBeanFactoryBasedTargetSourceCreator.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java index 4fd173f2893e..c18899db28f4 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java @@ -125,12 +125,7 @@ public final TargetSource getTargetSource(Class beanClass, String beanName) { */ protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) { synchronized (this.internalBeanFactories) { - DefaultListableBeanFactory internalBeanFactory = this.internalBeanFactories.get(beanName); - if (internalBeanFactory == null) { - internalBeanFactory = buildInternalBeanFactory(this.beanFactory); - this.internalBeanFactories.put(beanName, internalBeanFactory); - } - return internalBeanFactory; + return this.internalBeanFactories.computeIfAbsent(beanName, k -> buildInternalBeanFactory(this.beanFactory)); } } From ce94f69e525282b418f801e9d734070ad5cbfc45 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sat, 31 Jul 2021 16:30:39 +0200 Subject: [PATCH 030/140] Polish contribution See gh-27234 --- .../target/AbstractBeanFactoryBasedTargetSourceCreator.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java index c18899db28f4..fcef74b56ef4 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/target/AbstractBeanFactoryBasedTargetSourceCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2021 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. @@ -125,7 +125,8 @@ public final TargetSource getTargetSource(Class beanClass, String beanName) { */ protected DefaultListableBeanFactory getInternalBeanFactoryForBean(String beanName) { synchronized (this.internalBeanFactories) { - return this.internalBeanFactories.computeIfAbsent(beanName, k -> buildInternalBeanFactory(this.beanFactory)); + return this.internalBeanFactories.computeIfAbsent(beanName, + name -> buildInternalBeanFactory(this.beanFactory)); } } From 86ef0236e6581ca609091f3295e88f208e8f85d8 Mon Sep 17 00:00:00 2001 From: izeye Date: Wed, 4 Aug 2021 14:12:40 +0900 Subject: [PATCH 031/140] Polish printMvcResultsToWriterWithFailingGlobalResultMatcher() See gh-27238 --- .../resulthandlers/PrintingResultHandlerIntegrationTests.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java index d2a66f5178ba..9d47134e0fb6 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerIntegrationTests.java @@ -28,6 +28,7 @@ import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -70,6 +71,7 @@ void printMvcResultsToWriterWithFailingGlobalResultMatcher() throws Exception { .alwaysExpect(content().string("Boom!")) .build() .perform(get("/").content("Hello Request".getBytes()).characterEncoding("ISO-8859-1")); + fail("AssertionError is expected to be thrown."); } catch (AssertionError error) { assertThat(error).hasMessageContaining("Boom!"); From e290ae285cfc8d8e48b0685ce580262bef1a2688 Mon Sep 17 00:00:00 2001 From: Alexej Timonin Date: Fri, 30 Jul 2021 21:32:36 +0200 Subject: [PATCH 032/140] Improve Javadoc for ClientRequest#from See gh-27220 --- .../function/client/ClientRequest.java | 6 ++-- .../DefaultClientRequestBuilderTests.java | 35 ++++++++++++++++++- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java index 9e7cc31ba6b4..dc28e2bf7538 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -125,8 +125,8 @@ default Optional attribute(String name) { // Static builder methods /** - * Create a builder with the method, URI, headers, and cookies of the given request. - * @param other the request to copy the method, URI, headers, and cookies from + * Create a builder with the method, URI, headers, cookies, attributes, and body of the given request. + * @param other the request to copy the method, URI, headers, cookies, attributes, and body from * @return the created builder */ static Builder from(ClientRequest other) { diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java index 47fdfdf430f8..0788264acf7f 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -56,6 +56,8 @@ public void from() throws URISyntaxException { ClientRequest other = ClientRequest.create(GET, URI.create("https://example.com")) .header("foo", "bar") .cookie("baz", "qux") + .attribute("attributeKey", "attributeValue") + .attribute("anotherAttributeKey", "anotherAttributeValue") .httpRequest(request -> {}) .build(); ClientRequest result = ClientRequest.from(other) @@ -69,6 +71,37 @@ public void from() throws URISyntaxException { assertThat(result.cookies().size()).isEqualTo(1); assertThat(result.cookies().getFirst("baz")).isEqualTo("quux"); assertThat(result.httpRequest()).isNotNull(); + assertThat(result.attributes().get("attributeKey")).isEqualTo("attributeValue"); + assertThat(result.attributes().get("anotherAttributeKey")).isEqualTo("anotherAttributeValue"); + } + + @Test + public void fromCopiesBody() { + String body = "foo"; + BodyInserter inserter = (response, strategies) -> { + byte[] bodyBytes = body.getBytes(UTF_8); + DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.wrap(bodyBytes); + + return response.writeWith(Mono.just(buffer)); + }; + + ClientRequest other = ClientRequest.create(POST, URI.create("https://example.com")) + .body(inserter).build(); + + ClientRequest result = ClientRequest.from(other).build(); + + List> messageWriters = new ArrayList<>(); + messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes())); + + ExchangeStrategies strategies = mock(ExchangeStrategies.class); + given(strategies.messageWriters()).willReturn(messageWriters); + + MockClientHttpRequest request = new MockClientHttpRequest(POST, "/"); + result.writeTo(request, strategies).block(); + + String copiedBody = request.getBodyAsString().block(); + + assertThat(copiedBody).isEqualTo("foo"); } @Test From ce6217be8536944201a1215679870a57c414381d Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 3 Aug 2021 10:31:13 +0100 Subject: [PATCH 033/140] Polishing contribution Closes gh-27220 --- .../function/client/ClientRequest.java | 11 ++-- .../DefaultClientRequestBuilderTests.java | 59 ++++++++----------- 2 files changed, 30 insertions(+), 40 deletions(-) diff --git a/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java b/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java index dc28e2bf7538..2b61dba1836a 100644 --- a/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java +++ b/spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientRequest.java @@ -125,16 +125,17 @@ default Optional attribute(String name) { // Static builder methods /** - * Create a builder with the method, URI, headers, cookies, attributes, and body of the given request. - * @param other the request to copy the method, URI, headers, cookies, attributes, and body from - * @return the created builder + * Create a builder initialized with the HTTP method, url, headers, cookies, + * attributes, and body of the given request. + * @param other the request to copy from + * @return the builder instance */ static Builder from(ClientRequest other) { return new DefaultClientRequestBuilder(other); } /** - * Create a builder with the given method and url. + * Create a builder with the given HTTP method and url. * @param method the HTTP method (GET, POST, etc) * @param url the url (as a URI instance) * @return the created builder @@ -146,7 +147,7 @@ static Builder method(HttpMethod method, URI url) { } /** - * Create a request builder with the given method and url. + * Create a request builder with the given HTTP method and url. * @param method the HTTP method (GET, POST, etc) * @param url the url (as a URI instance) * @return the created builder diff --git a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java index 0788264acf7f..5bff972bdd2e 100644 --- a/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java +++ b/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultClientRequestBuilderTests.java @@ -51,20 +51,24 @@ */ public class DefaultClientRequestBuilderTests { + private static final URI DEFAULT_URL = URI.create("https://example.com"); + @Test - public void from() throws URISyntaxException { - ClientRequest other = ClientRequest.create(GET, URI.create("https://example.com")) + public void from() { + ClientRequest other = ClientRequest.create(GET, DEFAULT_URL) .header("foo", "bar") .cookie("baz", "qux") .attribute("attributeKey", "attributeValue") .attribute("anotherAttributeKey", "anotherAttributeValue") .httpRequest(request -> {}) .build(); + ClientRequest result = ClientRequest.from(other) .headers(httpHeaders -> httpHeaders.set("foo", "baar")) .cookies(cookies -> cookies.set("baz", "quux")) .build(); - assertThat(result.url()).isEqualTo(new URI("https://example.com")); + + assertThat(result.url()).isEqualTo(DEFAULT_URL); assertThat(result.method()).isEqualTo(GET); assertThat(result.headers().size()).isEqualTo(1); assertThat(result.headers().getFirst("foo")).isEqualTo("baar"); @@ -81,13 +85,10 @@ public void fromCopiesBody() { BodyInserter inserter = (response, strategies) -> { byte[] bodyBytes = body.getBytes(UTF_8); DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.wrap(bodyBytes); - return response.writeWith(Mono.just(buffer)); }; - ClientRequest other = ClientRequest.create(POST, URI.create("https://example.com")) - .body(inserter).build(); - + ClientRequest other = ClientRequest.create(POST, DEFAULT_URL).body(inserter).build(); ClientRequest result = ClientRequest.from(other).build(); List> messageWriters = new ArrayList<>(); @@ -105,9 +106,8 @@ public void fromCopiesBody() { } @Test - public void method() throws URISyntaxException { - URI url = new URI("https://example.com"); - ClientRequest.Builder builder = ClientRequest.create(DELETE, url); + public void method() { + ClientRequest.Builder builder = ClientRequest.create(DELETE, DEFAULT_URL); assertThat(builder.build().method()).isEqualTo(DELETE); builder.method(OPTIONS); @@ -127,18 +127,17 @@ public void url() throws URISyntaxException { @Test public void cookie() { - ClientRequest result = ClientRequest.create(GET, URI.create("https://example.com")) - .cookie("foo", "bar").build(); + ClientRequest result = ClientRequest.create(GET, DEFAULT_URL).cookie("foo", "bar").build(); assertThat(result.cookies().getFirst("foo")).isEqualTo("bar"); } @Test public void build() { - ClientRequest result = ClientRequest.create(GET, URI.create("https://example.com")) + ClientRequest result = ClientRequest.create(GET, DEFAULT_URL) .header("MyKey", "MyValue") .cookie("foo", "bar") .httpRequest(request -> { - MockClientHttpRequest nativeRequest = (MockClientHttpRequest) request.getNativeRequest(); + MockClientHttpRequest nativeRequest = request.getNativeRequest(); nativeRequest.getHeaders().add("MyKey2", "MyValue2"); }) .build(); @@ -158,16 +157,14 @@ public void build() { @Test public void bodyInserter() { String body = "foo"; - BodyInserter inserter = - (response, strategies) -> { - byte[] bodyBytes = body.getBytes(UTF_8); - DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.wrap(bodyBytes); + BodyInserter inserter = (response, strategies) -> { + byte[] bodyBytes = body.getBytes(UTF_8); + DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.wrap(bodyBytes); - return response.writeWith(Mono.just(buffer)); - }; + return response.writeWith(Mono.just(buffer)); + }; - ClientRequest result = ClientRequest.create(POST, URI.create("https://example.com")) - .body(inserter).build(); + ClientRequest result = ClientRequest.create(POST, DEFAULT_URL).body(inserter).build(); List> messageWriters = new ArrayList<>(); messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes())); @@ -179,17 +176,14 @@ public void bodyInserter() { result.writeTo(request, strategies).block(); assertThat(request.getBody()).isNotNull(); - StepVerifier.create(request.getBody()) - .expectNextCount(1) - .verifyComplete(); + StepVerifier.create(request.getBody()).expectNextCount(1).verifyComplete(); } @Test public void bodyClass() { String body = "foo"; Publisher publisher = Mono.just(body); - ClientRequest result = ClientRequest.create(POST, URI.create("https://example.com")) - .body(publisher, String.class).build(); + ClientRequest result = ClientRequest.create(POST, DEFAULT_URL).body(publisher, String.class).build(); List> messageWriters = new ArrayList<>(); messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes())); @@ -201,9 +195,7 @@ public void bodyClass() { result.writeTo(request, strategies).block(); assertThat(request.getBody()).isNotNull(); - StepVerifier.create(request.getBody()) - .expectNextCount(1) - .verifyComplete(); + StepVerifier.create(request.getBody()).expectNextCount(1).verifyComplete(); } @Test @@ -211,8 +203,7 @@ public void bodyParameterizedTypeReference() { String body = "foo"; Publisher publisher = Mono.just(body); ParameterizedTypeReference typeReference = new ParameterizedTypeReference() {}; - ClientRequest result = ClientRequest.create(POST, URI.create("https://example.com")) - .body(publisher, typeReference).build(); + ClientRequest result = ClientRequest.create(POST, DEFAULT_URL).body(publisher, typeReference).build(); List> messageWriters = new ArrayList<>(); messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes())); @@ -224,9 +215,7 @@ public void bodyParameterizedTypeReference() { result.writeTo(request, strategies).block(); assertThat(request.getBody()).isNotNull(); - StepVerifier.create(request.getBody()) - .expectNextCount(1) - .verifyComplete(); + StepVerifier.create(request.getBody()).expectNextCount(1).verifyComplete(); } } From eaf9deedfd06f2f324c05503f787b41f37c537c4 Mon Sep 17 00:00:00 2001 From: Syuziko Date: Sat, 7 Aug 2021 16:10:08 +0400 Subject: [PATCH 034/140] Polish tests See gh-27248 --- .../beans/AbstractPropertyAccessorTests.java | 155 +++++---- .../beans/BeanWrapperGenericsTests.java | 130 +++---- .../DefaultListableBeanFactoryTests.java | 34 +- .../support/BeanFactoryGenericsTests.java | 170 ++++----- .../ClassNameBeanWiringInfoResolverTests.java | 10 +- .../propertyeditors/CustomEditorTests.java | 322 +++++++++--------- .../aop/aspectj/ProceedTests.java | 4 +- .../AnnotationDrivenEventListenerTests.java | 76 ++--- .../jmx/export/MBeanExporterTests.java | 8 +- .../assembler/AbstractJmxAssemblerTests.java | 22 +- .../ScriptFactoryPostProcessorTests.java | 27 +- .../DataBinderFieldAccessTests.java | 20 +- .../validation/DataBinderTests.java | 204 +++++------ .../util/ObjectUtilsTests.java | 28 +- .../expression/spel/IndexingTests.java | 52 +-- .../expression/spel/OperatorTests.java | 68 ++-- .../spel/SpelCompilationCoverageTests.java | 166 ++++----- .../expression/spel/SpelReproTests.java | 220 ++++++------ .../adapter/MessageListenerAdapterTests.java | 55 ++- .../MappingJackson2MessageConverterTests.java | 41 +-- .../web/bind/EscapedErrorsTests.java | 2 +- .../web/bind/ServletRequestUtilsTests.java | 24 +- .../web/cors/CorsConfigurationTests.java | 48 +-- .../method/annotation/CrossOriginTests.java | 8 +- .../RedirectAttributesModelMapTests.java | 24 +- .../web/servlet/tags/BindTagTests.java | 78 ++--- .../servlet/tags/form/CheckboxTagTests.java | 58 ++-- .../tags/form/HiddenInputTagTests.java | 16 +- .../web/servlet/tags/form/InputTagTests.java | 2 +- .../web/servlet/tags/form/OptionTagTests.java | 52 +-- .../servlet/tags/form/OptionsTagTests.java | 46 +-- .../tags/form/RadioButtonTagTests.java | 28 +- .../web/servlet/tags/form/SelectTagTests.java | 8 +- .../servlet/tags/form/SimpleFloatEditor.java | 4 +- .../servlet/tags/form/TextareaTagTests.java | 2 +- .../view/RedirectViewUriTemplateTests.java | 24 +- 36 files changed, 1115 insertions(+), 1121 deletions(-) diff --git a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java index 0bb5febde05f..b0a3d012591d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -296,10 +296,10 @@ public void setNestedPropertyPolymorphic() throws Exception { accessor.setPropertyValue("spouse.age", 35); accessor.setPropertyValue("spouse.name", "Kerry"); accessor.setPropertyValue("spouse.company", "Lewisham"); - assertThat(kerry.getName().equals("Kerry")).as("kerry name is Kerry").isTrue(); + assertThat(kerry.getName()).as("kerry name is Kerry").isEqualTo("Kerry"); assertThat(target.getSpouse() == kerry).as("nested set worked").isTrue(); - assertThat(kerry.getSpouse() == null).as("no back relation").isTrue(); + assertThat(kerry.getSpouse()).as("no back relation").isNull(); accessor.setPropertyValue(new PropertyValue("spouse.spouse", target)); assertThat(kerry.getSpouse() == target).as("nested set worked").isTrue(); @@ -316,7 +316,7 @@ public void setAnotherNestedProperty() throws Exception { accessor.setPropertyValue("spouse", kerry); assertThat(target.getSpouse() == kerry).as("nested set worked").isTrue(); - assertThat(kerry.getSpouse() == null).as("no back relation").isTrue(); + assertThat(kerry.getSpouse()).as("no back relation").isNull(); accessor.setPropertyValue(new PropertyValue("spouse.spouse", target)); assertThat(kerry.getSpouse() == target).as("nested set worked").isTrue(); assertThat(kerry.getAge() == 0).as("kerry age not set").isTrue(); @@ -357,8 +357,7 @@ public void testErrorMessageOfNestedProperty() { AbstractPropertyAccessor accessor = createAccessor(target); try { accessor.getPropertyValue("spouse.bla"); - } - catch (NotReadablePropertyException ex) { + } catch (NotReadablePropertyException ex) { assertThat(ex.getMessage().contains(TestBean.class.getName())).isTrue(); } } @@ -478,8 +477,8 @@ public void setIndividualValidPropertyValues() { accessor.setPropertyValue("age", newAge); accessor.setPropertyValue(new PropertyValue("name", newName)); accessor.setPropertyValue(new PropertyValue("touchy", newTouchy)); - assertThat(target.getName().equals(newName)).as("Name property should have changed").isTrue(); - assertThat(target.getTouchy().equals(newTouchy)).as("Touchy property should have changed").isTrue(); + assertThat(target.getName()).as("Name property should have changed").isEqualTo(newName); + assertThat(target.getTouchy()).as("Touchy property should have changed").isEqualTo(newTouchy); assertThat(target.getAge() == newAge).as("Age property should have changed").isTrue(); } @@ -490,7 +489,7 @@ public void setPropertyIsReflectedImmediately() { AbstractPropertyAccessor accessor = createAccessor(target); target.setAge(newAge); Object bwAge = accessor.getPropertyValue("age"); - assertThat(bwAge instanceof Integer).as("Age is an integer").isTrue(); + assertThat(bwAge).as("Age is an integer").isInstanceOf(Integer.class); assertThat(bwAge).as("Bean wrapper must pick up changes").isEqualTo(newAge); } @@ -500,13 +499,13 @@ public void setPropertyToNull() { target.setName("Frank"); // we need to change it back target.setSpouse(target); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(target.getName() != null).as("name is not null to start off").isTrue(); + assertThat(target.getName()).as("name is not null to start off").isNotNull(); accessor.setPropertyValue("name", null); - assertThat(target.getName() == null).as("name is now null").isTrue(); + assertThat(target.getName()).as("name is now null").isNull(); // now test with non-string - assertThat(target.getSpouse() != null).as("spouse is not null to start off").isTrue(); + assertThat(target.getSpouse()).as("spouse is not null to start off").isNotNull(); accessor.setPropertyValue("spouse", null); - assertThat(target.getSpouse() == null).as("spouse is now null").isTrue(); + assertThat(target.getSpouse()).as("spouse is now null").isNull(); } @Test @@ -591,20 +590,20 @@ public void setNumberProperties() { accessor.setPropertyValue("float2", "8.1"); accessor.setPropertyValue("double2", "6.1"); accessor.setPropertyValue("bigDecimal", "4.0"); - assertThat(new Short("2").equals(accessor.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); - assertThat(new Short("2").equals(target.getShort2())).as("Correct short2 value").isTrue(); - assertThat(new Integer("8").equals(accessor.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); - assertThat(new Integer("8").equals(target.getInt2())).as("Correct int2 value").isTrue(); - assertThat(new Long("6").equals(accessor.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); - assertThat(new Long("6").equals(target.getLong2())).as("Correct long2 value").isTrue(); - assertThat(new BigInteger("3").equals(accessor.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); - assertThat(new BigInteger("3").equals(target.getBigInteger())).as("Correct bigInteger value").isTrue(); - assertThat(new Float("8.1").equals(accessor.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); - assertThat(new Float("8.1").equals(target.getFloat2())).as("Correct float2 value").isTrue(); - assertThat(new Double("6.1").equals(accessor.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); - assertThat(new Double("6.1").equals(target.getDouble2())).as("Correct double2 value").isTrue(); - assertThat(new BigDecimal("4.0").equals(accessor.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); - assertThat(new BigDecimal("4.0").equals(target.getBigDecimal())).as("Correct bigDecimal value").isTrue(); + assertThat(Short.valueOf("2")).as("Correct short2 value").isEqualTo(accessor.getPropertyValue("short2")); + assertThat(Short.valueOf("2")).as("Correct short2 value").isEqualTo(target.getShort2()); + assertThat(Integer.valueOf("8")).as("Correct int2 value").isEqualTo(accessor.getPropertyValue("int2")); + assertThat(Integer.valueOf("8")).as("Correct int2 value").isEqualTo(target.getInt2()); + assertThat(Long.valueOf("6")).as("Correct long2 value").isEqualTo(accessor.getPropertyValue("long2")); + assertThat(Long.valueOf("6")).as("Correct long2 value").isEqualTo(target.getLong2()); + assertThat(new BigInteger("3")).as("Correct bigInteger value").isEqualTo(accessor.getPropertyValue("bigInteger")); + assertThat(new BigInteger("3")).as("Correct bigInteger value").isEqualTo(target.getBigInteger()); + assertThat(Float.valueOf("8.1")).as("Correct float2 value").isEqualTo(accessor.getPropertyValue("float2")); + assertThat(Float.valueOf("8.1")).as("Correct float2 value").isEqualTo(target.getFloat2()); + assertThat(Double.valueOf("6.1").equals(accessor.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); + assertThat(Double.valueOf("6.1")).as("Correct double2 value").isEqualTo(target.getDouble2()); + assertThat(new BigDecimal("4.0")).as("Correct bigDecimal value").isEqualTo(accessor.getPropertyValue("bigDecimal")); + assertThat(new BigDecimal("4.0")).as("Correct bigDecimal value").isEqualTo(target.getBigDecimal()); } @Test @@ -616,22 +615,22 @@ public void setNumberPropertiesWithCoercion() { accessor.setPropertyValue("long2", new BigInteger("6")); accessor.setPropertyValue("bigInteger", 3L); accessor.setPropertyValue("float2", 8.1D); - accessor.setPropertyValue("double2", new BigDecimal(6.1)); + accessor.setPropertyValue("double2", new BigDecimal("6.1")); accessor.setPropertyValue("bigDecimal", 4.0F); - assertThat(new Short("2").equals(accessor.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); - assertThat(new Short("2").equals(target.getShort2())).as("Correct short2 value").isTrue(); - assertThat(new Integer("8").equals(accessor.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); - assertThat(new Integer("8").equals(target.getInt2())).as("Correct int2 value").isTrue(); - assertThat(new Long("6").equals(accessor.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); - assertThat(new Long("6").equals(target.getLong2())).as("Correct long2 value").isTrue(); + assertThat(Short.valueOf("2")).as("Correct short2 value").isEqualTo(accessor.getPropertyValue("short2")); + assertThat(Short.valueOf("2")).as("Correct short2 value").isEqualTo(target.getShort2()); + assertThat(Integer.valueOf("8")).as("Correct int2 value").isEqualTo(accessor.getPropertyValue("int2")); + assertThat(Integer.valueOf("8")).as("Correct int2 value").isEqualTo(target.getInt2()); + assertThat(Long.valueOf("6")).as("Correct long2 value").isEqualTo(accessor.getPropertyValue("long2")); + assertThat(Long.valueOf("6")).as("Correct long2 value").isEqualTo(target.getLong2()); assertThat(new BigInteger("3").equals(accessor.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); - assertThat(new BigInteger("3").equals(target.getBigInteger())).as("Correct bigInteger value").isTrue(); - assertThat(new Float("8.1").equals(accessor.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); - assertThat(new Float("8.1").equals(target.getFloat2())).as("Correct float2 value").isTrue(); - assertThat(new Double("6.1").equals(accessor.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); - assertThat(new Double("6.1").equals(target.getDouble2())).as("Correct double2 value").isTrue(); - assertThat(new BigDecimal("4.0").equals(accessor.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); - assertThat(new BigDecimal("4.0").equals(target.getBigDecimal())).as("Correct bigDecimal value").isTrue(); + assertThat(new BigInteger("3")).as("Correct bigInteger value").isEqualTo(target.getBigInteger()); + assertThat(Float.valueOf("8.1")).as("Correct float2 value").isEqualTo(accessor.getPropertyValue("float2")); + assertThat(Float.valueOf("8.1")).as("Correct float2 value").isEqualTo(target.getFloat2()); + assertThat(Double.valueOf("6.1")).as("Correct double2 value").isEqualTo(accessor.getPropertyValue("double2")); + assertThat(Double.valueOf("6.1")).as("Correct double2 value").isEqualTo(target.getDouble2()); + assertThat(new BigDecimal("4.0")).as("Correct bigDecimal value").isEqualTo(accessor.getPropertyValue("bigDecimal")); + assertThat(new BigDecimal("4.0")).as("Correct bigDecimal value").isEqualTo(target.getBigDecimal()); } @Test @@ -724,11 +723,11 @@ public void setPropertiesProperty() throws Exception { String ps = "peace=war\nfreedom=slavery"; accessor.setPropertyValue("properties", ps); - assertThat(target.name.equals("ptest")).as("name was set").isTrue(); - assertThat(target.properties != null).as("properties non null").isTrue(); + assertThat(target.name).as("name was set").isEqualTo("ptest"); + assertThat(target.properties).as("properties non null").isNotNull(); String freedomVal = target.properties.getProperty("freedom"); String peaceVal = target.properties.getProperty("peace"); - assertThat(peaceVal.equals("war")).as("peace==war").isTrue(); + assertThat(peaceVal).as("peace==war").isEqualTo("war"); assertThat(freedomVal.equals("slavery")).as("Freedom==slavery").isTrue(); } @@ -737,7 +736,7 @@ public void setStringArrayProperty() throws Exception { PropsTester target = new PropsTester(); AbstractPropertyAccessor accessor = createAccessor(target); - accessor.setPropertyValue("stringArray", new String[] {"foo", "fi", "fi", "fum"}); + accessor.setPropertyValue("stringArray", new String[]{"foo", "fi", "fi", "fum"}); assertThat(target.stringArray.length == 4).as("stringArray length = 4").isTrue(); assertThat(target.stringArray[0].equals("foo") && target.stringArray[1].equals("fi") && target.stringArray[2].equals("fi") && target.stringArray[3].equals("fum")).as("correct values").isTrue(); @@ -763,10 +762,10 @@ public void setStringArrayProperty() throws Exception { accessor.setPropertyValue("stringArray", "one"); assertThat(target.stringArray.length == 1).as("stringArray length = 1").isTrue(); - assertThat(target.stringArray[0].equals("one")).as("stringArray elt is ok").isTrue(); + assertThat(target.stringArray[0]).as("stringArray elt is ok").isEqualTo("one"); accessor.setPropertyValue("stringArray", null); - assertThat(target.stringArray == null).as("stringArray is null").isTrue(); + assertThat(target.stringArray).as("stringArray is null").isNull(); } @Test @@ -836,10 +835,10 @@ public void setStringArrayWithAutoGrow() throws Exception { accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("array[0]", "Test0"); - assertThat(target.getArray().length).isEqualTo(1); + assertThat(target.getArray()).hasSize(1); accessor.setPropertyValue("array[2]", "Test2"); - assertThat(target.getArray().length).isEqualTo(3); + assertThat(target.getArray()).hasSize(3); assertThat(target.getArray()[0].equals("Test0") && target.getArray()[1] == null && target.getArray()[2].equals("Test2")).as("correct values").isTrue(); } @@ -849,7 +848,7 @@ public void setIntArrayProperty() { PropsTester target = new PropsTester(); AbstractPropertyAccessor accessor = createAccessor(target); - accessor.setPropertyValue("intArray", new int[] {4, 5, 2, 3}); + accessor.setPropertyValue("intArray", new int[]{4, 5, 2, 3}); assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); @@ -910,21 +909,21 @@ public void setAsText(String text) { } }); - accessor.setPropertyValue("intArray", new int[] {4, 5, 2, 3}); + accessor.setPropertyValue("intArray", new int[]{4, 5, 2, 3}); assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && - target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); + target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); - accessor.setPropertyValue("intArray", new String[] {"3", "4", "1", "2"}); + accessor.setPropertyValue("intArray", new String[]{"3", "4", "1", "2"}); assertThat(target.intArray.length == 4).as("intArray length = 4").isTrue(); assertThat(target.intArray[0] == 4 && target.intArray[1] == 5 && - target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); + target.intArray[2] == 2 && target.intArray[3] == 3).as("correct values").isTrue(); accessor.setPropertyValue("intArray", 1); assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); assertThat(target.intArray[0] == 1).as("correct values").isTrue(); - accessor.setPropertyValue("intArray", new String[] {"0"}); + accessor.setPropertyValue("intArray", new String[]{"0"}); assertThat(target.intArray.length == 1).as("intArray length = 4").isTrue(); assertThat(target.intArray[0] == 1).as("correct values").isTrue(); @@ -947,8 +946,8 @@ public void setIntArrayPropertyWithStringSplitting() throws Exception { public void setPrimitiveArrayProperty() { PrimitiveArrayBean target = new PrimitiveArrayBean(); AbstractPropertyAccessor accessor = createAccessor(target); - accessor.setPropertyValue("array", new String[] {"1", "2"}); - assertThat(target.getArray().length).isEqualTo(2); + accessor.setPropertyValue("array", new String[]{"1", "2"}); + assertThat(target.getArray()).hasSize(2); assertThat(target.getArray()[0]).isEqualTo(1); assertThat(target.getArray()[1]).isEqualTo(2); } @@ -967,7 +966,7 @@ public void setValue(Object value) { }); int[] input = new int[1024]; accessor.setPropertyValue("array", input); - assertThat(target.getArray().length).isEqualTo(1024); + assertThat(target.getArray()).hasSize(1024); assertThat(target.getArray()[0]).isEqualTo(1); assertThat(target.getArray()[1]).isEqualTo(1); } @@ -986,8 +985,8 @@ public void setValue(Object value) { }); int[] input = new int[1024]; accessor.setPropertyValue("array", input); - assertThat(target.getArray().length).isEqualTo(1024); - assertThat(target.getArray()[0]).isEqualTo(0); + assertThat(target.getArray()).hasSize(1024); + assertThat(target.getArray()[0]).isZero(); assertThat(target.getArray()[1]).isEqualTo(1); } @@ -998,12 +997,12 @@ public void setPrimitiveArrayPropertyWithAutoGrow() throws Exception { accessor.setAutoGrowNestedPaths(true); accessor.setPropertyValue("array[0]", 1); - assertThat(target.getArray().length).isEqualTo(1); + assertThat(target.getArray()).hasSize(1); accessor.setPropertyValue("array[2]", 3); - assertThat(target.getArray().length).isEqualTo(3); + assertThat(target.getArray()).hasSize(3); assertThat(target.getArray()[0] == 1 && target.getArray()[1] == 0 && - target.getArray()[2] == 3).as("correct values").isTrue(); + target.getArray()[2] == 3).as("correct values").isTrue(); } @Test @@ -1018,7 +1017,7 @@ public void setGenericArrayProperty() { values.add("4"); accessor.setPropertyValue("items", values); Object[] result = target.items; - assertThat(result.length).isEqualTo(4); + assertThat(result).hasSize(4); assertThat(result[0]).isEqualTo("1"); assertThat(result[1]).isEqualTo("2"); assertThat(result[2]).isEqualTo("3"); @@ -1078,7 +1077,7 @@ public void setCollectionPropertyNonMatchingType() { Set list = new HashSet<>(); list.add("list1"); accessor.setPropertyValue("list", list); - assertThat(target.getCollection().size()).isEqualTo(1); + assertThat(target.getCollection()).hasSize(1); assertThat(target.getCollection().containsAll(coll)).isTrue(); assertThat(target.getSet().size()).isEqualTo(1); assertThat(target.getSet().containsAll(set)).isTrue(); @@ -1105,7 +1104,7 @@ public void setCollectionPropertyWithArrayValue() { Set list = new HashSet<>(); list.add("list1"); accessor.setPropertyValue("list", list.toArray()); - assertThat(target.getCollection().size()).isEqualTo(1); + assertThat(target.getCollection()).hasSize(1); assertThat(target.getCollection().containsAll(coll)).isTrue(); assertThat(target.getSet().size()).isEqualTo(1); assertThat(target.getSet().containsAll(set)).isTrue(); @@ -1122,17 +1121,17 @@ public void setCollectionPropertyWithIntArrayValue() { AbstractPropertyAccessor accessor = createAccessor(target); Collection coll = new HashSet<>(); coll.add(0); - accessor.setPropertyValue("collection", new int[] {0}); + accessor.setPropertyValue("collection", new int[]{0}); List set = new ArrayList<>(); set.add(1); - accessor.setPropertyValue("set", new int[] {1}); + accessor.setPropertyValue("set", new int[]{1}); List sortedSet = new ArrayList<>(); sortedSet.add(2); - accessor.setPropertyValue("sortedSet", new int[] {2}); + accessor.setPropertyValue("sortedSet", new int[]{2}); Set list = new HashSet<>(); list.add(3); - accessor.setPropertyValue("list", new int[] {3}); - assertThat(target.getCollection().size()).isEqualTo(1); + accessor.setPropertyValue("list", new int[]{3}); + assertThat(target.getCollection()).hasSize(1); assertThat(target.getCollection().containsAll(coll)).isTrue(); assertThat(target.getSet().size()).isEqualTo(1); assertThat(target.getSet().containsAll(set)).isTrue(); @@ -1159,7 +1158,7 @@ public void setCollectionPropertyWithIntegerValue() { Set list = new HashSet<>(); list.add(3); accessor.setPropertyValue("list", 3); - assertThat(target.getCollection().size()).isEqualTo(1); + assertThat(target.getCollection()).hasSize(1); assertThat(target.getCollection().containsAll(coll)).isTrue(); assertThat(target.getSet().size()).isEqualTo(1); assertThat(target.getSet().containsAll(set)).isTrue(); @@ -1236,7 +1235,7 @@ public void setMapPropertyNonMatchingType() { Map sortedMap = new TreeMap<>(); sortedMap.put("sortedKey", "sortedValue"); accessor.setPropertyValue("sortedMap", sortedMap); - assertThat(target.getMap().size()).isEqualTo(1); + assertThat(target.getMap()).hasSize(1); assertThat(target.getMap().get("key")).isEqualTo("value"); assertThat(target.getSortedMap().size()).isEqualTo(1); assertThat(target.getSortedMap().get("sortedKey")).isEqualTo("sortedValue"); @@ -1268,7 +1267,7 @@ public void setAsText(String text) throws IllegalArgumentException { badValues.add("map[key2]", ""); assertThatExceptionOfType(PropertyBatchUpdateException.class).isThrownBy(() -> accessor.setPropertyValues(badValues)) - .satisfies(ex -> assertThat(ex.getPropertyAccessException("map[key2]")).isInstanceOf(TypeMismatchException.class)); + .satisfies(ex -> assertThat(ex.getPropertyAccessException("map[key2]")).isInstanceOf(TypeMismatchException.class)); } @Test @@ -1319,7 +1318,7 @@ public void setAsText(String text) throws IllegalArgumentException { assertThat(((TestBean) target.getMap().get(2)).getName()).isEqualTo("rob"); } - @SuppressWarnings({ "unchecked", "rawtypes" }) // must work with raw map in this test + @SuppressWarnings({"unchecked", "rawtypes"}) // must work with raw map in this test @Test public void setRawMapPropertyWithNoEditorRegistered() { IndexedTestBean target = new IndexedTestBean(); @@ -1527,7 +1526,7 @@ public void getAndSetIndexedPropertiesWithDirectAccess() { assertThat((target.getList().get(0))).isEqualTo(tb3); assertThat((target.getList().get(1))).isEqualTo(tb2); assertThat((target.getList().get(2))).isEqualTo(tb0); - assertThat((target.getList().get(3))).isEqualTo(null); + assertThat((target.getList().get(3))).isNull(); assertThat((target.getList().get(4))).isEqualTo(tb1); assertThat((target.getMap().get("key1"))).isEqualTo(tb1); assertThat((target.getMap().get("key2"))).isEqualTo(tb0); @@ -1538,7 +1537,7 @@ public void getAndSetIndexedPropertiesWithDirectAccess() { assertThat(accessor.getPropertyValue("list[0]")).isEqualTo(tb3); assertThat(accessor.getPropertyValue("list[1]")).isEqualTo(tb2); assertThat(accessor.getPropertyValue("list[2]")).isEqualTo(tb0); - assertThat(accessor.getPropertyValue("list[3]")).isEqualTo(null); + assertThat(accessor.getPropertyValue("list[3]")).isNull(); assertThat(accessor.getPropertyValue("list[4]")).isEqualTo(tb1); assertThat(accessor.getPropertyValue("map[\"key1\"]")).isEqualTo(tb1); assertThat(accessor.getPropertyValue("map['key2']")).isEqualTo(tb0); @@ -1582,7 +1581,7 @@ public void propertyTypeDescriptorUnknownProperty() { public void propertyTypeIndexedProperty() { IndexedTestBean target = new IndexedTestBean(); AbstractPropertyAccessor accessor = createAccessor(target); - assertThat(accessor.getPropertyType("map[key0]")).isEqualTo(null); + assertThat(accessor.getPropertyType("map[key0]")).isNull(); accessor = createAccessor(target); accessor.setPropertyValue("map[key0]", "my String"); diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java index be0c2cc5953a..f5fef0b04a84 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -46,10 +46,10 @@ * @author Chris Beams * @since 18.01.2006 */ -public class BeanWrapperGenericsTests { +class BeanWrapperGenericsTests { @Test - public void testGenericSet() { + void testGenericSet() { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); Set input = new HashSet<>(); @@ -61,7 +61,7 @@ public void testGenericSet() { } @Test - public void testGenericLowerBoundedSet() { + void testGenericLowerBoundedSet() { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, true)); @@ -74,7 +74,7 @@ public void testGenericLowerBoundedSet() { } @Test - public void testGenericSetWithConversionFailure() { + void testGenericSetWithConversionFailure() { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); Set input = new HashSet<>(); @@ -85,7 +85,7 @@ public void testGenericSetWithConversionFailure() { } @Test - public void testGenericList() throws MalformedURLException { + void testGenericList() throws MalformedURLException { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); List input = new ArrayList<>(); @@ -97,7 +97,7 @@ public void testGenericList() throws MalformedURLException { } @Test - public void testGenericListElement() throws MalformedURLException { + void testGenericListElement() throws MalformedURLException { GenericBean gb = new GenericBean<>(); gb.setResourceList(new ArrayList<>()); BeanWrapper bw = new BeanWrapperImpl(gb); @@ -106,29 +106,29 @@ public void testGenericListElement() throws MalformedURLException { } @Test - public void testGenericMap() { + void testGenericMap() { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); Map input = new HashMap<>(); input.put("4", "5"); input.put("6", "7"); bw.setPropertyValue("shortMap", input); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); } @Test - public void testGenericMapElement() { + void testGenericMapElement() { GenericBean gb = new GenericBean<>(); gb.setShortMap(new HashMap<>()); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("shortMap[4]", "5"); assertThat(bw.getPropertyValue("shortMap[4]")).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); } @Test - public void testGenericMapWithKeyType() { + void testGenericMapWithKeyType() { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); Map input = new HashMap<>(); @@ -140,17 +140,17 @@ public void testGenericMapWithKeyType() { } @Test - public void testGenericMapElementWithKeyType() { + void testGenericMapElementWithKeyType() { GenericBean gb = new GenericBean<>(); gb.setLongMap(new HashMap()); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("longMap[4]", "5"); - assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5"); + assertThat(gb.getLongMap().get(Long.valueOf("4"))).isEqualTo("5"); assertThat(bw.getPropertyValue("longMap[4]")).isEqualTo("5"); } @Test - public void testGenericMapWithCollectionValue() { + void testGenericMapWithCollectionValue() { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)); @@ -169,7 +169,7 @@ public void testGenericMapWithCollectionValue() { } @Test - public void testGenericMapElementWithCollectionValue() { + void testGenericMapElementWithCollectionValue() { GenericBean gb = new GenericBean<>(); gb.setCollectionMap(new HashMap<>()); BeanWrapper bw = new BeanWrapperImpl(gb); @@ -182,19 +182,19 @@ public void testGenericMapElementWithCollectionValue() { } @Test - public void testGenericMapFromProperties() { + void testGenericMapFromProperties() { GenericBean gb = new GenericBean<>(); BeanWrapper bw = new BeanWrapperImpl(gb); Properties input = new Properties(); input.setProperty("4", "5"); input.setProperty("6", "7"); bw.setPropertyValue("shortMap", input); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); } @Test - public void testGenericListOfLists() throws MalformedURLException { + void testGenericListOfLists() throws MalformedURLException { GenericBean gb = new GenericBean<>(); List> list = new ArrayList<>(); list.add(new ArrayList<>()); @@ -206,7 +206,7 @@ public void testGenericListOfLists() throws MalformedURLException { } @Test - public void testGenericListOfListsWithElementConversion() throws MalformedURLException { + void testGenericListOfListsWithElementConversion() throws MalformedURLException { GenericBean gb = new GenericBean<>(); List> list = new ArrayList<>(); list.add(new ArrayList<>()); @@ -218,7 +218,7 @@ public void testGenericListOfListsWithElementConversion() throws MalformedURLExc } @Test - public void testGenericListOfArrays() throws MalformedURLException { + void testGenericListOfArrays() throws MalformedURLException { GenericBean gb = new GenericBean<>(); ArrayList list = new ArrayList<>(); list.add(new String[] {"str1", "str2"}); @@ -230,7 +230,7 @@ public void testGenericListOfArrays() throws MalformedURLException { } @Test - public void testGenericListOfArraysWithElementConversion() throws MalformedURLException { + void testGenericListOfArraysWithElementConversion() throws MalformedURLException { GenericBean gb = new GenericBean<>(); ArrayList list = new ArrayList<>(); list.add(new String[] {"str1", "str2"}); @@ -243,55 +243,55 @@ public void testGenericListOfArraysWithElementConversion() throws MalformedURLEx } @Test - public void testGenericListOfMaps() throws MalformedURLException { + void testGenericListOfMaps() throws MalformedURLException { GenericBean gb = new GenericBean<>(); List> list = new ArrayList<>(); list.add(new HashMap<>()); gb.setListOfMaps(list); BeanWrapper bw = new BeanWrapperImpl(gb); - bw.setPropertyValue("listOfMaps[0][10]", new Long(5)); - assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5)); - assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5)); + bw.setPropertyValue("listOfMaps[0][10]", 5L); + assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(5L); + assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(Long.valueOf(5)); } @Test - public void testGenericListOfMapsWithElementConversion() throws MalformedURLException { + void testGenericListOfMapsWithElementConversion() { GenericBean gb = new GenericBean<>(); List> list = new ArrayList<>(); list.add(new HashMap<>()); gb.setListOfMaps(list); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("listOfMaps[0][10]", "5"); - assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(new Long(5)); - assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(new Long(5)); + assertThat(bw.getPropertyValue("listOfMaps[0][10]")).isEqualTo(5L); + assertThat(gb.getListOfMaps().get(0).get(10)).isEqualTo(Long.valueOf(5)); } @Test - public void testGenericMapOfMaps() throws MalformedURLException { + void testGenericMapOfMaps() throws MalformedURLException { GenericBean gb = new GenericBean<>(); Map> map = new HashMap<>(); map.put("mykey", new HashMap<>()); gb.setMapOfMaps(map); BeanWrapper bw = new BeanWrapperImpl(gb); - bw.setPropertyValue("mapOfMaps[mykey][10]", new Long(5)); - assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5)); - assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5)); + bw.setPropertyValue("mapOfMaps[mykey][10]", 5L); + assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(5L); + assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(Long.valueOf(5)); } @Test - public void testGenericMapOfMapsWithElementConversion() throws MalformedURLException { + void testGenericMapOfMapsWithElementConversion() throws MalformedURLException { GenericBean gb = new GenericBean<>(); Map> map = new HashMap<>(); map.put("mykey", new HashMap<>()); gb.setMapOfMaps(map); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("mapOfMaps[mykey][10]", "5"); - assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(new Long(5)); - assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(new Long(5)); + assertThat(bw.getPropertyValue("mapOfMaps[mykey][10]")).isEqualTo(Long.valueOf(5)); + assertThat(gb.getMapOfMaps().get("mykey").get(10)).isEqualTo(Long.valueOf(5)); } @Test - public void testGenericMapOfLists() throws MalformedURLException { + void testGenericMapOfLists() throws MalformedURLException { GenericBean gb = new GenericBean<>(); Map> map = new HashMap<>(); map.put(1, new ArrayList<>()); @@ -303,7 +303,7 @@ public void testGenericMapOfLists() throws MalformedURLException { } @Test - public void testGenericMapOfListsWithElementConversion() throws MalformedURLException { + void testGenericMapOfListsWithElementConversion() throws MalformedURLException { GenericBean gb = new GenericBean<>(); Map> map = new HashMap<>(); map.put(1, new ArrayList<>()); @@ -315,7 +315,7 @@ public void testGenericMapOfListsWithElementConversion() throws MalformedURLExce } @Test - public void testGenericTypeNestingMapOfInteger() throws Exception { + void testGenericTypeNestingMapOfInteger() throws Exception { Map map = new HashMap<>(); map.put("testKey", "100"); @@ -329,9 +329,9 @@ public void testGenericTypeNestingMapOfInteger() throws Exception { } @Test - public void testGenericTypeNestingMapOfListOfInteger() throws Exception { + void testGenericTypeNestingMapOfListOfInteger() throws Exception { Map> map = new HashMap<>(); - List list = Arrays.asList(new String[] {"1", "2", "3"}); + List list = Arrays.asList("1", "2", "3"); map.put("testKey", list); NestedGenericCollectionBean gb = new NestedGenericCollectionBean(); @@ -345,7 +345,7 @@ public void testGenericTypeNestingMapOfListOfInteger() throws Exception { } @Test - public void testGenericTypeNestingListOfMapOfInteger() throws Exception { + void testGenericTypeNestingListOfMapOfInteger() throws Exception { List> list = new ArrayList<>(); Map map = new HashMap<>(); map.put("testKey", "5"); @@ -362,9 +362,9 @@ public void testGenericTypeNestingListOfMapOfInteger() throws Exception { } @Test - public void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception { + void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception { Map>> map = new HashMap<>(); - List list = Arrays.asList(new String[] {"1", "2", "3"}); + List list = Arrays.asList("1", "2", "3"); map.put("testKey", Collections.singletonList(list)); NestedGenericCollectionBean gb = new NestedGenericCollectionBean(); @@ -378,7 +378,7 @@ public void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception { } @Test - public void testComplexGenericMap() { + void testComplexGenericMap() { Map, List> inputMap = new HashMap<>(); List inputKey = new ArrayList<>(); inputKey.add("1"); @@ -391,11 +391,11 @@ public void testComplexGenericMap() { bw.setPropertyValue("genericMap", inputMap); assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(1); - assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); + assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10)); } @Test - public void testComplexGenericMapWithCollectionConversion() { + void testComplexGenericMapWithCollectionConversion() { Map, Set> inputMap = new HashMap<>(); Set inputKey = new HashSet<>(); inputKey.add("1"); @@ -408,11 +408,11 @@ public void testComplexGenericMapWithCollectionConversion() { bw.setPropertyValue("genericMap", inputMap); assertThat(holder.getGenericMap().keySet().iterator().next().get(0)).isEqualTo(1); - assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); + assertThat(holder.getGenericMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10)); } @Test - public void testComplexGenericIndexedMapEntry() { + void testComplexGenericIndexedMapEntry() { List inputValue = new ArrayList<>(); inputValue.add("10"); @@ -421,11 +421,11 @@ public void testComplexGenericIndexedMapEntry() { bw.setPropertyValue("genericIndexedMap[1]", inputValue); assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(1); - assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); + assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10)); } @Test - public void testComplexGenericIndexedMapEntryWithCollectionConversion() { + void testComplexGenericIndexedMapEntryWithCollectionConversion() { Set inputValue = new HashSet<>(); inputValue.add("10"); @@ -434,11 +434,11 @@ public void testComplexGenericIndexedMapEntryWithCollectionConversion() { bw.setPropertyValue("genericIndexedMap[1]", inputValue); assertThat(holder.getGenericIndexedMap().keySet().iterator().next()).isEqualTo(1); - assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); + assertThat(holder.getGenericIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10)); } @Test - public void testComplexDerivedIndexedMapEntry() { + void testComplexDerivedIndexedMapEntry() { List inputValue = new ArrayList<>(); inputValue.add("10"); @@ -447,11 +447,11 @@ public void testComplexDerivedIndexedMapEntry() { bw.setPropertyValue("derivedIndexedMap[1]", inputValue); assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(1); - assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); + assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10)); } @Test - public void testComplexDerivedIndexedMapEntryWithCollectionConversion() { + void testComplexDerivedIndexedMapEntryWithCollectionConversion() { Set inputValue = new HashSet<>(); inputValue.add("10"); @@ -460,11 +460,11 @@ public void testComplexDerivedIndexedMapEntryWithCollectionConversion() { bw.setPropertyValue("derivedIndexedMap[1]", inputValue); assertThat(holder.getDerivedIndexedMap().keySet().iterator().next()).isEqualTo(1); - assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(new Long(10)); + assertThat(holder.getDerivedIndexedMap().values().iterator().next().get(0)).isEqualTo(Long.valueOf(10)); } @Test - public void testGenericallyTypedIntegerBean() throws Exception { + void testGenericallyTypedIntegerBean() { GenericIntegerBean gb = new GenericIntegerBean(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("genericProperty", "10"); @@ -475,7 +475,7 @@ public void testGenericallyTypedIntegerBean() throws Exception { } @Test - public void testGenericallyTypedSetOfIntegerBean() throws Exception { + void testGenericallyTypedSetOfIntegerBean() { GenericSetOfIntegerBean gb = new GenericSetOfIntegerBean(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.setPropertyValue("genericProperty", "10"); @@ -486,23 +486,23 @@ public void testGenericallyTypedSetOfIntegerBean() throws Exception { } @Test - public void testSettingGenericPropertyWithReadOnlyInterface() { + void testSettingGenericPropertyWithReadOnlyInterface() { Bar bar = new Bar(); BeanWrapper bw = new BeanWrapperImpl(bar); bw.setPropertyValue("version", "10"); - assertThat(bar.getVersion()).isEqualTo(new Double(10.0)); + assertThat(bar.getVersion()).isEqualTo(Double.valueOf(10.0)); } @Test - public void testSettingLongPropertyWithGenericInterface() { + void testSettingLongPropertyWithGenericInterface() { Promotion bean = new Promotion(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("id", "10"); - assertThat(bean.getId()).isEqualTo(new Long(10)); + assertThat(bean.getId()).isEqualTo(Long.valueOf(10)); } @Test - public void testUntypedPropertyWithMapAtRuntime() { + void testUntypedPropertyWithMapAtRuntime() { class Holder { private final D data; public Holder(D data) { diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index 13321a7e9a2e..8d6f823a7583 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -182,9 +182,9 @@ void prototypeFactoryBeanIgnoredByNonEagerTypeMatching() { assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(0); + assertThat(beanNames).hasSize(0); beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class); - assertThat(beanNames.length).isEqualTo(0); + assertThat(beanNames).hasSize(0); assertThat(lbf.containsSingleton("x1")).isFalse(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -216,9 +216,9 @@ void singletonFactoryBeanIgnoredByNonEagerTypeMatching() { assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(0); + assertThat(beanNames).hasSize(0); beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class); - assertThat(beanNames.length).isEqualTo(0); + assertThat(beanNames).hasSize(0); assertThat(lbf.containsSingleton("x1")).isFalse(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -249,9 +249,9 @@ void nonInitializedFactoryBeanIgnoredByNonEagerTypeMatching() { assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(0); + assertThat(beanNames).hasSize(0); beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class); - assertThat(beanNames.length).isEqualTo(0); + assertThat(beanNames).hasSize(0); assertThat(lbf.containsSingleton("x1")).isFalse(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -283,7 +283,7 @@ void initializedFactoryBeanFoundByNonEagerTypeMatching() { assertThat(!DummyFactory.wasPrototypeCreated()).as("prototype not instantiated").isTrue(); String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames).hasSize(1); assertThat(beanNames[0]).isEqualTo("x1"); assertThat(lbf.containsSingleton("x1")).isTrue(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -337,7 +337,7 @@ void staticFactoryMethodFoundByNonEagerTypeMatching() { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames).hasSize(1); assertThat(beanNames[0]).isEqualTo("x1"); assertThat(lbf.containsSingleton("x1")).isFalse(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -349,7 +349,7 @@ void staticFactoryMethodFoundByNonEagerTypeMatching() { assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); - assertThat(lbf.getType("&x1")).isEqualTo(null); + assertThat(lbf.getType("&x1")).isNull(); assertThat(TestBeanFactory.initialized).isFalse(); } @@ -362,7 +362,7 @@ void staticPrototypeFactoryMethodFoundByNonEagerTypeMatching() { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames).hasSize(1); assertThat(beanNames[0]).isEqualTo("x1"); assertThat(lbf.containsSingleton("x1")).isFalse(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -374,7 +374,7 @@ void staticPrototypeFactoryMethodFoundByNonEagerTypeMatching() { assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); - assertThat(lbf.getType("&x1")).isEqualTo(null); + assertThat(lbf.getType("&x1")).isNull(); assertThat(TestBeanFactory.initialized).isFalse(); } @@ -389,7 +389,7 @@ void nonStaticFactoryMethodFoundByNonEagerTypeMatching() { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames).hasSize(1); assertThat(beanNames[0]).isEqualTo("x1"); assertThat(lbf.containsSingleton("x1")).isFalse(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -401,7 +401,7 @@ void nonStaticFactoryMethodFoundByNonEagerTypeMatching() { assertThat(lbf.isTypeMatch("x1", TestBean.class)).isTrue(); assertThat(lbf.isTypeMatch("&x1", TestBean.class)).isFalse(); assertThat(lbf.getType("x1")).isEqualTo(TestBean.class); - assertThat(lbf.getType("&x1")).isEqualTo(null); + assertThat(lbf.getType("&x1")).isNull(); assertThat(TestBeanFactory.initialized).isFalse(); } @@ -417,7 +417,7 @@ void nonStaticPrototypeFactoryMethodFoundByNonEagerTypeMatching() { TestBeanFactory.initialized = false; String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false); - assertThat(beanNames.length).isEqualTo(1); + assertThat(beanNames).hasSize(1); assertThat(beanNames[0]).isEqualTo("x1"); assertThat(lbf.containsSingleton("x1")).isFalse(); assertThat(lbf.containsBean("x1")).isTrue(); @@ -450,7 +450,7 @@ void nonStaticPrototypeFactoryMethodFoundByNonEagerTypeMatching() { assertThat(lbf.isTypeMatch("x2", Object.class)).isTrue(); assertThat(lbf.isTypeMatch("&x2", Object.class)).isFalse(); assertThat(lbf.getType("x2")).isEqualTo(TestBean.class); - assertThat(lbf.getType("&x2")).isEqualTo(null); + assertThat(lbf.getType("&x2")).isNull(); assertThat(lbf.getAliases("x1").length).isEqualTo(1); assertThat(lbf.getAliases("x1")[0]).isEqualTo("x2"); assertThat(lbf.getAliases("&x1").length).isEqualTo(1); @@ -3030,7 +3030,7 @@ public CustomTypeConverter(NumberFormat numberFormat) { public Object convertIfNecessary(Object value, @Nullable Class requiredType) { if (value instanceof String && Float.class.isAssignableFrom(requiredType)) { try { - return new Float(this.numberFormat.parse((String) value).floatValue()); + return this.numberFormat.parse((String) value).floatValue(); } catch (ParseException ex) { throw new TypeMismatchException(value, requiredType, ex); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java index e3ba7b5d93f1..5a981f91e54c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -64,10 +64,10 @@ * @author Sam Brannen * @since 20.01.2006 */ -public class BeanFactoryGenericsTests { +class BeanFactoryGenericsTests { @Test - public void testGenericSetProperty() { + void testGenericSetProperty() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -84,7 +84,7 @@ public void testGenericSetProperty() { } @Test - public void testGenericListProperty() throws Exception { + void testGenericListProperty() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -101,7 +101,7 @@ public void testGenericListProperty() throws Exception { } @Test - public void testGenericListPropertyWithAutowiring() throws Exception { + void testGenericListPropertyWithAutowiring() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerSingleton("resource1", new UrlResource("http://localhost:8080")); bf.registerSingleton("resource2", new UrlResource("http://localhost:9090")); @@ -116,7 +116,7 @@ public void testGenericListPropertyWithAutowiring() throws Exception { } @Test - public void testGenericListPropertyWithInvalidElementType() { + void testGenericListPropertyWithInvalidElementType() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericIntegerBean.class); @@ -134,7 +134,7 @@ public void testGenericListPropertyWithInvalidElementType() { } @Test - public void testGenericListPropertyWithOptionalAutowiring() { + void testGenericListPropertyWithOptionalAutowiring() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -146,7 +146,7 @@ public void testGenericListPropertyWithOptionalAutowiring() { } @Test - public void testGenericMapProperty() { + void testGenericMapProperty() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -158,12 +158,12 @@ public void testGenericMapProperty() { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); } @Test - public void testGenericListOfArraysProperty() { + void testGenericListOfArraysProperty() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); @@ -171,14 +171,14 @@ public void testGenericListOfArraysProperty() { assertThat(gb.getListOfArrays().size()).isEqualTo(1); String[] array = gb.getListOfArrays().get(0); - assertThat(array.length).isEqualTo(2); + assertThat(array).hasSize(2); assertThat(array[0]).isEqualTo("value1"); assertThat(array[1]).isEqualTo("value2"); } @Test - public void testGenericSetConstructor() { + void testGenericSetConstructor() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -195,7 +195,7 @@ public void testGenericSetConstructor() { } @Test - public void testGenericSetConstructorWithAutowiring() { + void testGenericSetConstructorWithAutowiring() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerSingleton("integer1", 4); bf.registerSingleton("integer2", 5); @@ -210,7 +210,7 @@ public void testGenericSetConstructorWithAutowiring() { } @Test - public void testGenericSetConstructorWithOptionalAutowiring() { + void testGenericSetConstructorWithOptionalAutowiring() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -222,7 +222,7 @@ public void testGenericSetConstructorWithOptionalAutowiring() { } @Test - public void testGenericSetListConstructor() throws Exception { + void testGenericSetListConstructor() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -245,7 +245,7 @@ public void testGenericSetListConstructor() throws Exception { } @Test - public void testGenericSetListConstructorWithAutowiring() throws Exception { + void testGenericSetListConstructorWithAutowiring() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerSingleton("integer1", 4); bf.registerSingleton("integer2", 5); @@ -264,7 +264,7 @@ public void testGenericSetListConstructorWithAutowiring() throws Exception { } @Test - public void testGenericSetListConstructorWithOptionalAutowiring() throws Exception { + void testGenericSetListConstructorWithOptionalAutowiring() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerSingleton("resource1", new UrlResource("http://localhost:8080")); bf.registerSingleton("resource2", new UrlResource("http://localhost:9090")); @@ -279,7 +279,7 @@ public void testGenericSetListConstructorWithOptionalAutowiring() throws Excepti } @Test - public void testGenericSetMapConstructor() { + void testGenericSetMapConstructor() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -297,12 +297,12 @@ public void testGenericSetMapConstructor() { assertThat(gb.getIntegerSet().contains(4)).isTrue(); assertThat(gb.getIntegerSet().contains(5)).isTrue(); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); } @Test - public void testGenericMapResourceConstructor() throws Exception { + void testGenericMapResourceConstructor() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -315,13 +315,13 @@ public void testGenericMapResourceConstructor() throws Exception { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); } @Test - public void testGenericMapMapConstructor() { + void testGenericMapMapConstructor() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -338,16 +338,16 @@ public void testGenericMapMapConstructor() { GenericBean gb = (GenericBean) bf.getBean("genericBean"); assertThat(gb.getShortMap()).isNotSameAs(gb.getPlainMap()); - assertThat(gb.getPlainMap().size()).isEqualTo(2); + assertThat(gb.getPlainMap()).hasSize(2); assertThat(gb.getPlainMap().get("1")).isEqualTo("0"); assertThat(gb.getPlainMap().get("2")).isEqualTo("3"); assertThat(gb.getShortMap().size()).isEqualTo(2); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); } @Test - public void testGenericMapMapConstructorWithSameRefAndConversion() { + void testGenericMapMapConstructorWithSameRefAndConversion() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -361,22 +361,22 @@ public void testGenericMapMapConstructorWithSameRefAndConversion() { GenericBean gb = (GenericBean) bf.getBean("genericBean"); assertThat(gb.getShortMap()).isNotSameAs(gb.getPlainMap()); - assertThat(gb.getPlainMap().size()).isEqualTo(2); + assertThat(gb.getPlainMap()).hasSize(2); assertThat(gb.getPlainMap().get("1")).isEqualTo("0"); assertThat(gb.getPlainMap().get("2")).isEqualTo("3"); assertThat(gb.getShortMap().size()).isEqualTo(2); - assertThat(gb.getShortMap().get(new Short("1"))).isEqualTo(0); - assertThat(gb.getShortMap().get(new Short("2"))).isEqualTo(3); + assertThat(gb.getShortMap().get(Short.valueOf("1"))).isEqualTo(0); + assertThat(gb.getShortMap().get(Short.valueOf("2"))).isEqualTo(3); } @Test - public void testGenericMapMapConstructorWithSameRefAndNoConversion() { + void testGenericMapMapConstructorWithSameRefAndNoConversion() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); Map input = new HashMap<>(); - input.put(new Short((short) 1), 0); - input.put(new Short((short) 2), 3); + input.put((short) 1, 0); + input.put((short) 2, 3); rbd.getConstructorArgumentValues().addGenericArgumentValue(input); rbd.getConstructorArgumentValues().addGenericArgumentValue(input); @@ -384,13 +384,13 @@ public void testGenericMapMapConstructorWithSameRefAndNoConversion() { GenericBean gb = (GenericBean) bf.getBean("genericBean"); assertThat(gb.getShortMap()).isSameAs(gb.getPlainMap()); - assertThat(gb.getShortMap().size()).isEqualTo(2); - assertThat(gb.getShortMap().get(new Short("1"))).isEqualTo(0); - assertThat(gb.getShortMap().get(new Short("2"))).isEqualTo(3); + assertThat(gb.getShortMap()).hasSize(2); + assertThat(gb.getShortMap().get(Short.valueOf("1"))).isEqualTo(0); + assertThat(gb.getShortMap().get(Short.valueOf("2"))).isEqualTo(3); } @Test - public void testGenericMapWithKeyTypeConstructor() { + void testGenericMapWithKeyTypeConstructor() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); @@ -407,7 +407,7 @@ public void testGenericMapWithKeyTypeConstructor() { } @Test - public void testGenericMapWithCollectionValueConstructor() { + void testGenericMapWithCollectionValueConstructor() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { @Override @@ -438,7 +438,7 @@ public void registerCustomEditors(PropertyEditorRegistry registry) { @Test - public void testGenericSetFactoryMethod() { + void testGenericSetFactoryMethod() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); rbd.setFactoryMethodName("createInstance"); @@ -456,7 +456,7 @@ public void testGenericSetFactoryMethod() { } @Test - public void testGenericSetListFactoryMethod() throws Exception { + void testGenericSetListFactoryMethod() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); rbd.setFactoryMethodName("createInstance"); @@ -480,7 +480,7 @@ public void testGenericSetListFactoryMethod() throws Exception { } @Test - public void testGenericSetMapFactoryMethod() { + void testGenericSetMapFactoryMethod() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); rbd.setFactoryMethodName("createInstance"); @@ -499,12 +499,12 @@ public void testGenericSetMapFactoryMethod() { assertThat(gb.getIntegerSet().contains(4)).isTrue(); assertThat(gb.getIntegerSet().contains(5)).isTrue(); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); } @Test - public void testGenericMapResourceFactoryMethod() throws Exception { + void testGenericMapResourceFactoryMethod() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); rbd.setFactoryMethodName("createInstance"); @@ -518,13 +518,13 @@ public void testGenericMapResourceFactoryMethod() throws Exception { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); assertThat(gb.getResourceList().get(0)).isEqualTo(new UrlResource("http://localhost:8080")); } @Test - public void testGenericMapMapFactoryMethod() { + void testGenericMapMapFactoryMethod() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); rbd.setFactoryMethodName("createInstance"); @@ -543,12 +543,12 @@ public void testGenericMapMapFactoryMethod() { assertThat(gb.getPlainMap().get("1")).isEqualTo("0"); assertThat(gb.getPlainMap().get("2")).isEqualTo("3"); - assertThat(gb.getShortMap().get(new Short("4"))).isEqualTo(5); - assertThat(gb.getShortMap().get(new Short("6"))).isEqualTo(7); + assertThat(gb.getShortMap().get(Short.valueOf("4"))).isEqualTo(5); + assertThat(gb.getShortMap().get(Short.valueOf("6"))).isEqualTo(7); } @Test - public void testGenericMapWithKeyTypeFactoryMethod() { + void testGenericMapWithKeyTypeFactoryMethod() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class); rbd.setFactoryMethodName("createInstance"); @@ -561,12 +561,12 @@ public void testGenericMapWithKeyTypeFactoryMethod() { bf.registerBeanDefinition("genericBean", rbd); GenericBean gb = (GenericBean) bf.getBean("genericBean"); - assertThat(gb.getLongMap().get(new Long("4"))).isEqualTo("5"); - assertThat(gb.getLongMap().get(new Long("6"))).isEqualTo("7"); + assertThat(gb.getLongMap().get(Long.valueOf("4"))).isEqualTo("5"); + assertThat(gb.getLongMap().get(Long.valueOf("6"))).isEqualTo("7"); } @Test - public void testGenericMapWithCollectionValueFactoryMethod() { + void testGenericMapWithCollectionValueFactoryMethod() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() { @Override @@ -597,7 +597,7 @@ public void registerCustomEditors(PropertyEditorRegistry registry) { } @Test - public void testGenericListBean() throws Exception { + void testGenericListBean() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); @@ -607,7 +607,7 @@ public void testGenericListBean() throws Exception { } @Test - public void testGenericSetBean() throws Exception { + void testGenericSetBean() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); @@ -617,18 +617,18 @@ public void testGenericSetBean() throws Exception { } @Test - public void testGenericMapBean() throws Exception { + void testGenericMapBean() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); Map map = (Map) bf.getBean("map"); - assertThat(map.size()).isEqualTo(1); + assertThat(map).hasSize(1); assertThat(map.keySet().iterator().next()).isEqualTo(10); assertThat(map.values().iterator().next()).isEqualTo(new URL("http://localhost:8080")); } @Test - public void testGenericallyTypedIntegerBean() { + void testGenericallyTypedIntegerBean() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); @@ -639,7 +639,7 @@ public void testGenericallyTypedIntegerBean() { } @Test - public void testGenericallyTypedSetOfIntegerBean() { + void testGenericallyTypedSetOfIntegerBean() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); @@ -651,7 +651,7 @@ public void testGenericallyTypedSetOfIntegerBean() { @Test @EnabledForTestGroups(LONG_RUNNING) - public void testSetBean() throws Exception { + void testSetBean() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions( new ClassPathResource("genericBeanTests.xml", getClass())); @@ -671,7 +671,7 @@ public void testSetBean() throws Exception { *

    See SPR-9493 */ @Test - public void parameterizedStaticFactoryMethod() { + void parameterizedStaticFactoryMethod() { RootBeanDefinition rbd = new RootBeanDefinition(Mockito.class); rbd.setFactoryMethodName("mock"); rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class); @@ -682,7 +682,7 @@ public void parameterizedStaticFactoryMethod() { assertThat(bf.getType("mock")).isEqualTo(Runnable.class); assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertThat(beans.size()).isEqualTo(1); + assertThat(beans).hasSize(1); } /** @@ -697,7 +697,7 @@ public void parameterizedStaticFactoryMethod() { *

    See SPR-10411 */ @Test - public void parameterizedInstanceFactoryMethod() { + void parameterizedInstanceFactoryMethod() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class); @@ -714,11 +714,11 @@ public void parameterizedInstanceFactoryMethod() { assertThat(bf.getType("mock")).isEqualTo(Runnable.class); assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertThat(beans.size()).isEqualTo(1); + assertThat(beans).hasSize(1); } @Test - public void parameterizedInstanceFactoryMethodWithNonResolvedClassName() { + void parameterizedInstanceFactoryMethodWithNonResolvedClassName() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class); @@ -735,11 +735,11 @@ public void parameterizedInstanceFactoryMethodWithNonResolvedClassName() { assertThat(bf.getType("mock")).isEqualTo(Runnable.class); assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertThat(beans.size()).isEqualTo(1); + assertThat(beans).hasSize(1); } @Test - public void parameterizedInstanceFactoryMethodWithWrappedClassName() { + void parameterizedInstanceFactoryMethodWithWrappedClassName() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(); @@ -754,11 +754,11 @@ public void parameterizedInstanceFactoryMethodWithWrappedClassName() { assertThat(bf.getType("mock")).isEqualTo(Runnable.class); assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertThat(beans.size()).isEqualTo(1); + assertThat(beans).hasSize(1); } @Test - public void parameterizedInstanceFactoryMethodWithInvalidClassName() { + void parameterizedInstanceFactoryMethodWithInvalidClassName() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class); @@ -775,11 +775,11 @@ public void parameterizedInstanceFactoryMethodWithInvalidClassName() { assertThat(bf.getType("mock")).isNull(); assertThat(bf.getType("mock")).isNull(); Map beans = bf.getBeansOfType(Runnable.class); - assertThat(beans.size()).isEqualTo(0); + assertThat(beans).hasSize(0); } @Test - public void parameterizedInstanceFactoryMethodWithIndexedArgument() { + void parameterizedInstanceFactoryMethodWithIndexedArgument() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(MocksControl.class); @@ -796,11 +796,11 @@ public void parameterizedInstanceFactoryMethodWithIndexedArgument() { assertThat(bf.getType("mock")).isEqualTo(Runnable.class); assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertThat(beans.size()).isEqualTo(1); + assertThat(beans).hasSize(1); } @Test // SPR-16720 - public void parameterizedInstanceFactoryMethodWithTempClassLoader() { + void parameterizedInstanceFactoryMethodWithTempClassLoader() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setTempClassLoader(new OverridingClassLoader(getClass().getClassLoader())); @@ -818,11 +818,11 @@ public void parameterizedInstanceFactoryMethodWithTempClassLoader() { assertThat(bf.getType("mock")).isEqualTo(Runnable.class); assertThat(bf.getType("mock")).isEqualTo(Runnable.class); Map beans = bf.getBeansOfType(Runnable.class); - assertThat(beans.size()).isEqualTo(1); + assertThat(beans).hasSize(1); } @Test - public void testGenericMatchingWithBeanNameDifferentiation() { + void testGenericMatchingWithBeanNameDifferentiation() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver()); @@ -838,15 +838,15 @@ public void testGenericMatchingWithBeanNameDifferentiation() { String[] numberStoreNames = bf.getBeanNamesForType(ResolvableType.forClass(NumberStore.class)); String[] doubleStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class)); String[] floatStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class)); - assertThat(numberStoreNames.length).isEqualTo(2); + assertThat(numberStoreNames).hasSize(2); assertThat(numberStoreNames[0]).isEqualTo("doubleStore"); assertThat(numberStoreNames[1]).isEqualTo("floatStore"); - assertThat(doubleStoreNames.length).isEqualTo(0); - assertThat(floatStoreNames.length).isEqualTo(0); + assertThat(doubleStoreNames).hasSize(0); + assertThat(floatStoreNames).hasSize(0); } @Test - public void testGenericMatchingWithFullTypeDifferentiation() { + void testGenericMatchingWithFullTypeDifferentiation() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver()); @@ -867,12 +867,12 @@ public void testGenericMatchingWithFullTypeDifferentiation() { String[] numberStoreNames = bf.getBeanNamesForType(ResolvableType.forClass(NumberStore.class)); String[] doubleStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Double.class)); String[] floatStoreNames = bf.getBeanNamesForType(ResolvableType.forClassWithGenerics(NumberStore.class, Float.class)); - assertThat(numberStoreNames.length).isEqualTo(2); + assertThat(numberStoreNames).hasSize(2); assertThat(numberStoreNames[0]).isEqualTo("store1"); assertThat(numberStoreNames[1]).isEqualTo("store2"); - assertThat(doubleStoreNames.length).isEqualTo(1); + assertThat(doubleStoreNames).hasSize(1); assertThat(doubleStoreNames[0]).isEqualTo("store1"); - assertThat(floatStoreNames.length).isEqualTo(1); + assertThat(floatStoreNames).hasSize(1); assertThat(floatStoreNames[0]).isEqualTo("store2"); ObjectProvider> numberStoreProvider = bf.getBeanProvider(ResolvableType.forClass(NumberStore.class)); @@ -938,7 +938,7 @@ public void testGenericMatchingWithFullTypeDifferentiation() { } @Test - public void testGenericMatchingWithUnresolvedOrderedStream() { + void testGenericMatchingWithUnresolvedOrderedStream() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); bf.setAutowireCandidateResolver(new GenericTypeAwareAutowireCandidateResolver()); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java index 67cef6f11665..becb7961f2a3 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -26,18 +26,18 @@ * * @author Rick Evans */ -public class ClassNameBeanWiringInfoResolverTests { +class ClassNameBeanWiringInfoResolverTests { @Test - public void resolveWiringInfoWithNullBeanInstance() throws Exception { + void resolveWiringInfoWithNullBeanInstance() throws Exception { assertThatIllegalArgumentException().isThrownBy(() -> new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null)); } @Test - public void resolveWiringInfo() { + void resolveWiringInfo() { ClassNameBeanWiringInfoResolver resolver = new ClassNameBeanWiringInfoResolver(); - Long beanInstance = new Long(1); + Long beanInstance = 1L; BeanWiringInfo info = resolver.resolveWiringInfo(beanInstance); assertThat(info).isNotNull(); assertThat(info.getBeanName()).as("Not resolving bean name to the class name of the supplied bean instance as per class contract.").isEqualTo(beanInstance.getClass().getName()); diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java index 0de98a10f002..36fc01ddc649 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,6 +16,10 @@ package org.springframework.beans.propertyeditors; +import org.junit.jupiter.api.Test; +import org.springframework.beans.*; +import org.springframework.beans.testfixture.beans.*; + import java.beans.PropertyEditor; import java.beans.PropertyEditorSupport; import java.beans.PropertyVetoException; @@ -64,10 +68,10 @@ * @author Chris Beams * @since 10.06.2003 */ -public class CustomEditorTests { +class CustomEditorTests { @Test - public void testComplexObject() { + void testComplexObject() { TestBean tb = new TestBean(); String newName = "Rod"; String tbString = "Kerry_34"; @@ -80,12 +84,12 @@ public void testComplexObject() { pvs.addPropertyValue(new PropertyValue("touchy", "valid")); pvs.addPropertyValue(new PropertyValue("spouse", tbString)); bw.setPropertyValues(pvs); - assertThat(tb.getSpouse() != null).as("spouse is non-null").isTrue(); + assertThat(tb.getSpouse()).as("spouse is non-null").isNotNull(); assertThat(tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34).as("spouse name is Kerry and age is 34").isTrue(); } @Test - public void testComplexObjectWithOldValueAccess() { + void testComplexObjectWithOldValueAccess() { TestBean tb = new TestBean(); String newName = "Rod"; String tbString = "Kerry_34"; @@ -100,7 +104,7 @@ public void testComplexObjectWithOldValueAccess() { pvs.addPropertyValue(new PropertyValue("spouse", tbString)); bw.setPropertyValues(pvs); - assertThat(tb.getSpouse() != null).as("spouse is non-null").isTrue(); + assertThat(tb.getSpouse()).as("spouse is non-null").isNotNull(); assertThat(tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34).as("spouse name is Kerry and age is 34").isTrue(); ITestBean spouse = tb.getSpouse(); @@ -109,7 +113,7 @@ public void testComplexObjectWithOldValueAccess() { } @Test - public void testCustomEditorForSingleProperty() { + void testCustomEditorForSingleProperty() { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() { @@ -127,7 +131,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testCustomEditorForAllStringProperties() { + void testCustomEditorForAllStringProperties() { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, new PropertyEditorSupport() { @@ -145,7 +149,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testCustomEditorForSingleNestedProperty() { + void testCustomEditorForSingleNestedProperty() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -164,7 +168,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testCustomEditorForAllNestedStringProperties() { + void testCustomEditorForAllNestedStringProperties() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -183,7 +187,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testDefaultBooleanEditorForPrimitiveType() { + void testDefaultBooleanEditorForPrimitiveType() { BooleanTestBean tb = new BooleanTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -229,7 +233,7 @@ public void testDefaultBooleanEditorForPrimitiveType() { } @Test - public void testDefaultBooleanEditorForWrapperType() { + void testDefaultBooleanEditorForWrapperType() { BooleanTestBean tb = new BooleanTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -239,28 +243,28 @@ public void testDefaultBooleanEditorForWrapperType() { bw.setPropertyValue("bool2", "false"); assertThat(Boolean.FALSE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); - boolean condition3 = !tb.getBool2().booleanValue(); + boolean condition3 = !tb.getBool2(); assertThat(condition3).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "on"); assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "off"); - boolean condition2 = !tb.getBool2().booleanValue(); + boolean condition2 = !tb.getBool2(); assertThat(condition2).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "yes"); assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "no"); - boolean condition1 = !tb.getBool2().booleanValue(); + boolean condition1 = !tb.getBool2(); assertThat(condition1).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "1"); assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "0"); - boolean condition = !tb.getBool2().booleanValue(); + boolean condition = !tb.getBool2(); assertThat(condition).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", ""); @@ -268,7 +272,7 @@ public void testDefaultBooleanEditorForWrapperType() { } @Test - public void testCustomBooleanEditorWithAllowEmpty() { + void testCustomBooleanEditorWithAllowEmpty() { BooleanTestBean tb = new BooleanTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true)); @@ -279,37 +283,37 @@ public void testCustomBooleanEditorWithAllowEmpty() { bw.setPropertyValue("bool2", "false"); assertThat(Boolean.FALSE.equals(bw.getPropertyValue("bool2"))).as("Correct bool2 value").isTrue(); - boolean condition3 = !tb.getBool2().booleanValue(); + boolean condition3 = !tb.getBool2(); assertThat(condition3).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "on"); assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "off"); - boolean condition2 = !tb.getBool2().booleanValue(); + boolean condition2 = !tb.getBool2(); assertThat(condition2).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "yes"); assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "no"); - boolean condition1 = !tb.getBool2().booleanValue(); + boolean condition1 = !tb.getBool2(); assertThat(condition1).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "1"); assertThat(tb.getBool2().booleanValue()).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", "0"); - boolean condition = !tb.getBool2().booleanValue(); + boolean condition = !tb.getBool2(); assertThat(condition).as("Correct bool2 value").isTrue(); bw.setPropertyValue("bool2", ""); - assertThat(bw.getPropertyValue("bool2") == null).as("Correct bool2 value").isTrue(); - assertThat(tb.getBool2() == null).as("Correct bool2 value").isTrue(); + assertThat(bw.getPropertyValue("bool2")).as("Correct bool2 value").isNull(); + assertThat(tb.getBool2()).as("Correct bool2 value").isNull(); } @Test - public void testCustomBooleanEditorWithSpecialTrueAndFalseStrings() throws Exception { + void testCustomBooleanEditorWithSpecialTrueAndFalseStrings() throws Exception { String trueString = "pechorin"; String falseString = "nash"; @@ -333,7 +337,7 @@ public void testCustomBooleanEditorWithSpecialTrueAndFalseStrings() throws Excep } @Test - public void testDefaultNumberEditor() { + void testDefaultNumberEditor() { NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -350,34 +354,34 @@ public void testDefaultNumberEditor() { bw.setPropertyValue("double2", "6.1"); bw.setPropertyValue("bigDecimal", "4.5"); - assertThat(new Short("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue(); + assertThat(Short.valueOf("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue(); assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue(); - assertThat(new Short("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); - assertThat(new Short("2").equals(tb.getShort2())).as("Correct short2 value").isTrue(); - assertThat(new Integer("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue(); + assertThat(Short.valueOf("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); + assertThat(Short.valueOf("2").equals(tb.getShort2())).as("Correct short2 value").isTrue(); + assertThat(Integer.valueOf("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue(); assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue(); - assertThat(new Integer("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); - assertThat(new Integer("8").equals(tb.getInt2())).as("Correct int2 value").isTrue(); - assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); + assertThat(Integer.valueOf("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); + assertThat(Integer.valueOf("8").equals(tb.getInt2())).as("Correct int2 value").isTrue(); + assertThat(Long.valueOf("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); - assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); - assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); + assertThat(Long.valueOf("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); + assertThat(Long.valueOf("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); assertThat(new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); assertThat(new BigInteger("3").equals(tb.getBigInteger())).as("Correct bigInteger value").isTrue(); - assertThat(new Float("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue(); - assertThat(new Float("7.1").equals(new Float(tb.getFloat1()))).as("Correct float1 value").isTrue(); - assertThat(new Float("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); - assertThat(new Float("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue(); - assertThat(new Double("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue(); + assertThat(Float.valueOf("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue(); + assertThat(Float.valueOf("7.1").equals(tb.getFloat1())).as("Correct float1 value").isTrue(); + assertThat(Float.valueOf("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); + assertThat(Float.valueOf("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue(); + assertThat(Double.valueOf("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue(); assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue(); - assertThat(new Double("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); - assertThat(new Double("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue(); + assertThat(Double.valueOf("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); + assertThat(Double.valueOf("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue(); assertThat(new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); assertThat(new BigDecimal("4.5").equals(tb.getBigDecimal())).as("Correct bigDecimal value").isTrue(); } @Test - public void testCustomNumberEditorWithoutAllowEmpty() { + void testCustomNumberEditorWithoutAllowEmpty() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -407,34 +411,34 @@ public void testCustomNumberEditorWithoutAllowEmpty() { bw.setPropertyValue("double2", "6,1"); bw.setPropertyValue("bigDecimal", "4,5"); - assertThat(new Short("1").equals(bw.getPropertyValue("short1"))).as("Correct short1 value").isTrue(); + assertThat(bw.getPropertyValue("short1")).as("Correct short1 value").isEqualTo(Short.valueOf("1")); assertThat(tb.getShort1() == 1).as("Correct short1 value").isTrue(); - assertThat(new Short("2").equals(bw.getPropertyValue("short2"))).as("Correct short2 value").isTrue(); - assertThat(new Short("2").equals(tb.getShort2())).as("Correct short2 value").isTrue(); - assertThat(new Integer("7").equals(bw.getPropertyValue("int1"))).as("Correct int1 value").isTrue(); + assertThat(bw.getPropertyValue("short2")).as("Correct short2 value").isEqualTo(Short.valueOf("2")); + assertThat(tb.getShort2()).as("Correct short2 value").isEqualTo(Short.valueOf("2")); + assertThat(bw.getPropertyValue("int1")).as("Correct int1 value").isEqualTo(Integer.valueOf("7")); assertThat(tb.getInt1() == 7).as("Correct int1 value").isTrue(); - assertThat(new Integer("8").equals(bw.getPropertyValue("int2"))).as("Correct int2 value").isTrue(); - assertThat(new Integer("8").equals(tb.getInt2())).as("Correct int2 value").isTrue(); - assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); + assertThat(bw.getPropertyValue("int2")).as("Correct int2 value").isEqualTo(Integer.valueOf("8")); + assertThat(tb.getInt2()).as("Correct int2 value").isEqualTo(Integer.valueOf("8")); + assertThat(bw.getPropertyValue("long1")).as("Correct long1 value").isEqualTo(Long.valueOf("5")); assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); - assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); - assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); + assertThat(bw.getPropertyValue("long2")).as("Correct long2 value").isEqualTo(Long.valueOf("6")); + assertThat(tb.getLong2()).as("Correct long2 value").isEqualTo(Long.valueOf("6")); assertThat(new BigInteger("3").equals(bw.getPropertyValue("bigInteger"))).as("Correct bigInteger value").isTrue(); assertThat(new BigInteger("3").equals(tb.getBigInteger())).as("Correct bigInteger value").isTrue(); - assertThat(new Float("7.1").equals(bw.getPropertyValue("float1"))).as("Correct float1 value").isTrue(); - assertThat(new Float("7.1").equals(new Float(tb.getFloat1()))).as("Correct float1 value").isTrue(); - assertThat(new Float("8.1").equals(bw.getPropertyValue("float2"))).as("Correct float2 value").isTrue(); - assertThat(new Float("8.1").equals(tb.getFloat2())).as("Correct float2 value").isTrue(); - assertThat(new Double("5.1").equals(bw.getPropertyValue("double1"))).as("Correct double1 value").isTrue(); + assertThat(bw.getPropertyValue("float1")).as("Correct float1 value").isEqualTo(Float.valueOf("7.1")); + assertThat(Float.valueOf(tb.getFloat1())).as("Correct float1 value").isEqualTo(Float.valueOf("7.1")); + assertThat(bw.getPropertyValue("float2")).as("Correct float2 value").isEqualTo(Float.valueOf("8.1")); + assertThat(tb.getFloat2()).as("Correct float2 value").isEqualTo(Float.valueOf("8.1")); + assertThat(bw.getPropertyValue("double1")).as("Correct double1 value").isEqualTo(Double.valueOf("5.1")); assertThat(tb.getDouble1() == 5.1).as("Correct double1 value").isTrue(); - assertThat(new Double("6.1").equals(bw.getPropertyValue("double2"))).as("Correct double2 value").isTrue(); - assertThat(new Double("6.1").equals(tb.getDouble2())).as("Correct double2 value").isTrue(); + assertThat(bw.getPropertyValue("double2")).as("Correct double2 value").isEqualTo(Double.valueOf("6.1")); + assertThat(tb.getDouble2()).as("Correct double2 value").isEqualTo(Double.valueOf("6.1")); assertThat(new BigDecimal("4.5").equals(bw.getPropertyValue("bigDecimal"))).as("Correct bigDecimal value").isTrue(); assertThat(new BigDecimal("4.5").equals(tb.getBigDecimal())).as("Correct bigDecimal value").isTrue(); } @Test - public void testCustomNumberEditorWithAllowEmpty() { + void testCustomNumberEditorWithAllowEmpty() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -443,10 +447,10 @@ public void testCustomNumberEditorWithAllowEmpty() { bw.setPropertyValue("long1", "5"); bw.setPropertyValue("long2", "6"); - assertThat(new Long("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); + assertThat(Long.valueOf("5").equals(bw.getPropertyValue("long1"))).as("Correct long1 value").isTrue(); assertThat(tb.getLong1() == 5).as("Correct long1 value").isTrue(); - assertThat(new Long("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); - assertThat(new Long("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); + assertThat(Long.valueOf("6").equals(bw.getPropertyValue("long2"))).as("Correct long2 value").isTrue(); + assertThat(Long.valueOf("6").equals(tb.getLong2())).as("Correct long2 value").isTrue(); bw.setPropertyValue("long2", ""); assertThat(bw.getPropertyValue("long2") == null).as("Correct long2 value").isTrue(); @@ -458,7 +462,7 @@ public void testCustomNumberEditorWithAllowEmpty() { } @Test - public void testCustomNumberEditorWithFrenchBigDecimal() throws Exception { + void testCustomNumberEditorWithFrenchBigDecimal() throws Exception { NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRENCH); NumberTestBean tb = new NumberTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); @@ -475,14 +479,14 @@ public void testCustomNumberEditorWithFrenchBigDecimal() throws Exception { } @Test - public void testParseShortGreaterThanMaxValueWithoutNumberFormat() { + void testParseShortGreaterThanMaxValueWithoutNumberFormat() { CustomNumberEditor editor = new CustomNumberEditor(Short.class, true); assertThatExceptionOfType(NumberFormatException.class).as("greater than Short.MAX_VALUE + 1").isThrownBy(() -> editor.setAsText(String.valueOf(Short.MAX_VALUE + 1))); } @Test - public void testByteArrayPropertyEditor() { + void testByteArrayPropertyEditor() { PrimitiveArrayBean bean = new PrimitiveArrayBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("byteArray", "myvalue"); @@ -490,7 +494,7 @@ public void testByteArrayPropertyEditor() { } @Test - public void testCharArrayPropertyEditor() { + void testCharArrayPropertyEditor() { PrimitiveArrayBean bean = new PrimitiveArrayBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.setPropertyValue("charArray", "myvalue"); @@ -498,7 +502,7 @@ public void testCharArrayPropertyEditor() { } @Test - public void testCharacterEditor() { + void testCharacterEditor() { CharBean cb = new CharBean(); BeanWrapper bw = new BeanWrapperImpl(cb); @@ -520,78 +524,78 @@ public void testCharacterEditor() { } @Test - public void testCharacterEditorWithAllowEmpty() { + void testCharacterEditorWithAllowEmpty() { CharBean cb = new CharBean(); BeanWrapper bw = new BeanWrapperImpl(cb); bw.registerCustomEditor(Character.class, new CharacterEditor(true)); - bw.setPropertyValue("myCharacter", new Character('c')); - assertThat(cb.getMyCharacter()).isEqualTo(new Character('c')); + bw.setPropertyValue("myCharacter", 'c'); + assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf('c')); bw.setPropertyValue("myCharacter", "c"); - assertThat(cb.getMyCharacter()).isEqualTo(new Character('c')); + assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf('c')); bw.setPropertyValue("myCharacter", "\u0041"); - assertThat(cb.getMyCharacter()).isEqualTo(new Character('A')); + assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf('A')); bw.setPropertyValue("myCharacter", " "); - assertThat(cb.getMyCharacter()).isEqualTo(new Character(' ')); + assertThat(cb.getMyCharacter()).isEqualTo(Character.valueOf(' ')); bw.setPropertyValue("myCharacter", ""); assertThat(cb.getMyCharacter()).isNull(); } @Test - public void testCharacterEditorSetAsTextWithStringLongerThanOneCharacter() throws Exception { + void testCharacterEditorSetAsTextWithStringLongerThanOneCharacter() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); assertThatIllegalArgumentException().isThrownBy(() -> charEditor.setAsText("ColdWaterCanyon")); } @Test - public void testCharacterEditorGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception { + void testCharacterEditorGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); - assertThat(charEditor.getAsText()).isEqualTo(""); + assertThat(charEditor.getAsText()).isEmpty(); charEditor = new CharacterEditor(true); charEditor.setAsText(null); - assertThat(charEditor.getAsText()).isEqualTo(""); + assertThat(charEditor.getAsText()).isEmpty(); charEditor.setAsText(""); - assertThat(charEditor.getAsText()).isEqualTo(""); + assertThat(charEditor.getAsText()).isEmpty(); charEditor.setAsText(" "); assertThat(charEditor.getAsText()).isEqualTo(" "); } @Test - public void testCharacterEditorSetAsTextWithNullNotAllowingEmptyAsNull() throws Exception { + void testCharacterEditorSetAsTextWithNullNotAllowingEmptyAsNull() throws Exception { PropertyEditor charEditor = new CharacterEditor(false); assertThatIllegalArgumentException().isThrownBy(() -> charEditor.setAsText(null)); } @Test - public void testClassEditor() { + void testClassEditor() { PropertyEditor classEditor = new ClassEditor(); classEditor.setAsText(TestBean.class.getName()); assertThat(classEditor.getValue()).isEqualTo(TestBean.class); assertThat(classEditor.getAsText()).isEqualTo(TestBean.class.getName()); classEditor.setAsText(null); - assertThat(classEditor.getAsText()).isEqualTo(""); + assertThat(classEditor.getAsText()).isEmpty(); classEditor.setAsText(""); - assertThat(classEditor.getAsText()).isEqualTo(""); + assertThat(classEditor.getAsText()).isEmpty(); classEditor.setAsText("\t "); - assertThat(classEditor.getAsText()).isEqualTo(""); + assertThat(classEditor.getAsText()).isEmpty(); } @Test - public void testClassEditorWithNonExistentClass() throws Exception { + void testClassEditorWithNonExistentClass() throws Exception { PropertyEditor classEditor = new ClassEditor(); assertThatIllegalArgumentException().isThrownBy(() -> classEditor.setAsText("hairdresser.on.Fire")); } @Test - public void testClassEditorWithArray() { + void testClassEditorWithArray() { PropertyEditor classEditor = new ClassEditor(); classEditor.setAsText("org.springframework.beans.testfixture.beans.TestBean[]"); assertThat(classEditor.getValue()).isEqualTo(TestBean[].class); @@ -602,7 +606,7 @@ public void testClassEditorWithArray() { * SPR_2165 - ClassEditor is inconsistent with multidimensional arrays */ @Test - public void testGetAsTextWithTwoDimensionalArray() throws Exception { + void testGetAsTextWithTwoDimensionalArray() throws Exception { String[][] chessboard = new String[8][8]; ClassEditor editor = new ClassEditor(); editor.setValue(chessboard.getClass()); @@ -613,7 +617,7 @@ public void testGetAsTextWithTwoDimensionalArray() throws Exception { * SPR_2165 - ClassEditor is inconsistent with multidimensional arrays */ @Test - public void testGetAsTextWithRidiculousMultiDimensionalArray() throws Exception { + void testGetAsTextWithRidiculousMultiDimensionalArray() throws Exception { String[][][][][] ridiculousChessboard = new String[8][4][0][1][3]; ClassEditor editor = new ClassEditor(); editor.setValue(ridiculousChessboard.getClass()); @@ -621,7 +625,7 @@ public void testGetAsTextWithRidiculousMultiDimensionalArray() throws Exception } @Test - public void testFileEditor() { + void testFileEditor() { PropertyEditor fileEditor = new FileEditor(); fileEditor.setAsText("file:myfile.txt"); assertThat(fileEditor.getValue()).isEqualTo(new File("myfile.txt")); @@ -629,7 +633,7 @@ public void testFileEditor() { } @Test - public void testFileEditorWithRelativePath() { + void testFileEditorWithRelativePath() { PropertyEditor fileEditor = new FileEditor(); try { fileEditor.setAsText("myfile.txt"); @@ -641,7 +645,7 @@ public void testFileEditorWithRelativePath() { } @Test - public void testFileEditorWithAbsolutePath() { + void testFileEditorWithAbsolutePath() { PropertyEditor fileEditor = new FileEditor(); // testing on Windows if (new File("C:/myfile.txt").isAbsolute()) { @@ -656,18 +660,18 @@ public void testFileEditorWithAbsolutePath() { } @Test - public void testLocaleEditor() { + void testLocaleEditor() { PropertyEditor localeEditor = new LocaleEditor(); localeEditor.setAsText("en_CA"); assertThat(localeEditor.getValue()).isEqualTo(Locale.CANADA); assertThat(localeEditor.getAsText()).isEqualTo("en_CA"); localeEditor = new LocaleEditor(); - assertThat(localeEditor.getAsText()).isEqualTo(""); + assertThat(localeEditor.getAsText()).isEmpty(); } @Test - public void testPatternEditor() { + void testPatternEditor() { final String REGEX = "a.*"; PropertyEditor patternEditor = new PatternEditor(); @@ -676,15 +680,15 @@ public void testPatternEditor() { assertThat(patternEditor.getAsText()).isEqualTo(REGEX); patternEditor = new PatternEditor(); - assertThat(patternEditor.getAsText()).isEqualTo(""); + assertThat(patternEditor.getAsText()).isEmpty(); patternEditor = new PatternEditor(); patternEditor.setAsText(null); - assertThat(patternEditor.getAsText()).isEqualTo(""); + assertThat(patternEditor.getAsText()).isEmpty(); } @Test - public void testCustomBooleanEditor() { + void testCustomBooleanEditor() { CustomBooleanEditor editor = new CustomBooleanEditor(false); editor.setAsText("true"); @@ -696,15 +700,15 @@ public void testCustomBooleanEditor() { assertThat(editor.getAsText()).isEqualTo("false"); editor.setValue(null); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText(null)); } @Test - public void testCustomBooleanEditorWithEmptyAsNull() { + void testCustomBooleanEditorWithEmptyAsNull() { CustomBooleanEditor editor = new CustomBooleanEditor(true); editor.setAsText("true"); @@ -716,76 +720,76 @@ public void testCustomBooleanEditorWithEmptyAsNull() { assertThat(editor.getAsText()).isEqualTo("false"); editor.setValue(null); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testCustomDateEditor() { + void testCustomDateEditor() { CustomDateEditor editor = new CustomDateEditor(null, false); editor.setValue(null); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testCustomDateEditorWithEmptyAsNull() { + void testCustomDateEditorWithEmptyAsNull() { CustomDateEditor editor = new CustomDateEditor(null, true); editor.setValue(null); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testCustomDateEditorWithExactDateLength() { + void testCustomDateEditorWithExactDateLength() { int maxLength = 10; String validDate = "01/01/2005"; String invalidDate = "01/01/05"; - assertThat(validDate.length() == maxLength).isTrue(); - assertThat(invalidDate.length() == maxLength).isFalse(); + assertThat(validDate).hasSize(maxLength); + assertThat(invalidDate.length()).isNotEqualTo(maxLength); CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true, maxLength); editor.setAsText(validDate); assertThatIllegalArgumentException().isThrownBy(() -> editor.setAsText(invalidDate)) - .withMessageContaining("10"); + .withMessageContaining("10"); } @Test - public void testCustomNumberEditor() { + void testCustomNumberEditor() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false); editor.setAsText("5"); assertThat(editor.getValue()).isEqualTo(5); assertThat(editor.getAsText()).isEqualTo("5"); editor.setValue(null); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testCustomNumberEditorWithHex() { + void testCustomNumberEditorWithHex() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, false); editor.setAsText("0x" + Integer.toHexString(64)); assertThat(editor.getValue()).isEqualTo(64); } @Test - public void testCustomNumberEditorWithEmptyAsNull() { + void testCustomNumberEditorWithEmptyAsNull() { CustomNumberEditor editor = new CustomNumberEditor(Integer.class, true); editor.setAsText("5"); assertThat(editor.getValue()).isEqualTo(5); assertThat(editor.getAsText()).isEqualTo("5"); editor.setAsText(""); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); editor.setValue(null); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testStringTrimmerEditor() { + void testStringTrimmerEditor() { StringTrimmerEditor editor = new StringTrimmerEditor(false); editor.setAsText("test"); assertThat(editor.getValue()).isEqualTo("test"); @@ -795,15 +799,15 @@ public void testStringTrimmerEditor() { assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(""); assertThat(editor.getValue()).isEqualTo(""); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); editor.setValue(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); editor.setAsText(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testStringTrimmerEditorWithEmptyAsNull() { + void testStringTrimmerEditorWithEmptyAsNull() { StringTrimmerEditor editor = new StringTrimmerEditor(true); editor.setAsText("test"); assertThat(editor.getValue()).isEqualTo("test"); @@ -812,14 +816,14 @@ public void testStringTrimmerEditorWithEmptyAsNull() { assertThat(editor.getValue()).isEqualTo("test"); assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" "); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); editor.setValue(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testStringTrimmerEditorWithCharsToDelete() { + void testStringTrimmerEditorWithCharsToDelete() { StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", false); editor.setAsText("te\ns\ft"); assertThat(editor.getValue()).isEqualTo("test"); @@ -829,13 +833,13 @@ public void testStringTrimmerEditorWithCharsToDelete() { assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(""); assertThat(editor.getValue()).isEqualTo(""); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); editor.setValue(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testStringTrimmerEditorWithCharsToDeleteAndEmptyAsNull() { + void testStringTrimmerEditorWithCharsToDeleteAndEmptyAsNull() { StringTrimmerEditor editor = new StringTrimmerEditor("\r\n\f", true); editor.setAsText("te\ns\ft"); assertThat(editor.getValue()).isEqualTo("test"); @@ -844,14 +848,14 @@ public void testStringTrimmerEditorWithCharsToDeleteAndEmptyAsNull() { assertThat(editor.getValue()).isEqualTo("test"); assertThat(editor.getAsText()).isEqualTo("test"); editor.setAsText(" \n\f "); - assertThat(editor.getValue()).isEqualTo(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getValue()).isNull(); + assertThat(editor.getAsText()).isEmpty(); editor.setValue(null); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testIndexedPropertiesWithCustomEditorForType() { + void testIndexedPropertiesWithCustomEditorForType() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, new PropertyEditorSupport() { @@ -904,7 +908,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testIndexedPropertiesWithCustomEditorForProperty() { + void testIndexedPropertiesWithCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(false); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, "array.name", new PropertyEditorSupport() { @@ -971,7 +975,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testIndexedPropertiesWithIndividualCustomEditorForProperty() { + void testIndexedPropertiesWithIndividualCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(false); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(String.class, "array[0].name", new PropertyEditorSupport() { @@ -1056,7 +1060,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testNestedIndexedPropertiesWithCustomEditorForProperty() { + void testNestedIndexedPropertiesWithCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; @@ -1140,7 +1144,7 @@ public String getAsText() { } @Test - public void testNestedIndexedPropertiesWithIndexedCustomEditorForProperty() { + void testNestedIndexedPropertiesWithIndexedCustomEditorForProperty() { IndexedTestBean bean = new IndexedTestBean(); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; @@ -1191,7 +1195,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testIndexedPropertiesWithDirectAccessAndPropertyEditors() { + void testIndexedPropertiesWithDirectAccessAndPropertyEditors() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(TestBean.class, "array", new PropertyEditorSupport() { @@ -1245,7 +1249,7 @@ public String getAsText() { } @Test - public void testIndexedPropertiesWithDirectAccessAndSpecificPropertyEditors() { + void testIndexedPropertiesWithDirectAccessAndSpecificPropertyEditors() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(TestBean.class, "array[0]", new PropertyEditorSupport() { @@ -1332,7 +1336,7 @@ public String getAsText() { } @Test - public void testIndexedPropertiesWithListPropertyEditor() { + void testIndexedPropertiesWithListPropertyEditor() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor(List.class, "list", new PropertyEditorSupport() { @@ -1350,7 +1354,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testConversionToOldCollections() throws PropertyVetoException { + void testConversionToOldCollections() throws PropertyVetoException { OldCollectionsBean tb = new OldCollectionsBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(Vector.class, new CustomCollectionEditor(Vector.class)); @@ -1367,7 +1371,7 @@ public void testConversionToOldCollections() throws PropertyVetoException { } @Test - public void testUninitializedArrayPropertyWithCustomEditor() { + void testUninitializedArrayPropertyWithCustomEditor() { IndexedTestBean bean = new IndexedTestBean(false); BeanWrapper bw = new BeanWrapperImpl(bean); PropertyEditor pe = new CustomNumberEditor(Integer.class, true); @@ -1383,7 +1387,7 @@ public void testUninitializedArrayPropertyWithCustomEditor() { } @Test - public void testArrayToArrayConversion() throws PropertyVetoException { + void testArrayToArrayConversion() throws PropertyVetoException { IndexedTestBean tb = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(TestBean.class, new PropertyEditorSupport() { @@ -1399,7 +1403,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testArrayToStringConversion() throws PropertyVetoException { + void testArrayToStringConversion() throws PropertyVetoException { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor(String.class, new PropertyEditorSupport() { @@ -1408,16 +1412,16 @@ public void setAsText(String text) throws IllegalArgumentException { setValue("-" + text + "-"); } }); - bw.setPropertyValue("name", new String[] {"a", "b"}); + bw.setPropertyValue("name", new String[]{"a", "b"}); assertThat(tb.getName()).isEqualTo("-a,b-"); } @Test - public void testClassArrayEditorSunnyDay() throws Exception { + void testClassArrayEditorSunnyDay() throws Exception { ClassArrayEditor classArrayEditor = new ClassArrayEditor(); classArrayEditor.setAsText("java.lang.String,java.util.HashMap"); Class[] classes = (Class[]) classArrayEditor.getValue(); - assertThat(classes.length).isEqualTo(2); + assertThat(classes).hasSize(2); assertThat(classes[0]).isEqualTo(String.class); assertThat(classes[1]).isEqualTo(HashMap.class); assertThat(classArrayEditor.getAsText()).isEqualTo("java.lang.String,java.util.HashMap"); @@ -1426,11 +1430,11 @@ public void testClassArrayEditorSunnyDay() throws Exception { } @Test - public void testClassArrayEditorSunnyDayWithArrayTypes() throws Exception { + void testClassArrayEditorSunnyDayWithArrayTypes() throws Exception { ClassArrayEditor classArrayEditor = new ClassArrayEditor(); classArrayEditor.setAsText("java.lang.String[],java.util.Map[],int[],float[][][]"); Class[] classes = (Class[]) classArrayEditor.getValue(); - assertThat(classes.length).isEqualTo(4); + assertThat(classes).hasSize(4); assertThat(classes[0]).isEqualTo(String[].class); assertThat(classes[1]).isEqualTo(Map[].class); assertThat(classes[2]).isEqualTo(int[].class); @@ -1441,31 +1445,31 @@ public void testClassArrayEditorSunnyDayWithArrayTypes() throws Exception { } @Test - public void testClassArrayEditorSetAsTextWithNull() throws Exception { + void testClassArrayEditorSetAsTextWithNull() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText(null); assertThat(editor.getValue()).isNull(); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testClassArrayEditorSetAsTextWithEmptyString() throws Exception { + void testClassArrayEditorSetAsTextWithEmptyString() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText(""); assertThat(editor.getValue()).isNull(); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testClassArrayEditorSetAsTextWithWhitespaceString() throws Exception { + void testClassArrayEditorSetAsTextWithWhitespaceString() throws Exception { ClassArrayEditor editor = new ClassArrayEditor(); editor.setAsText("\n"); assertThat(editor.getValue()).isNull(); - assertThat(editor.getAsText()).isEqualTo(""); + assertThat(editor.getAsText()).isEmpty(); } @Test - public void testCharsetEditor() throws Exception { + void testCharsetEditor() throws Exception { CharsetEditor editor = new CharsetEditor(); String name = "UTF-8"; editor.setAsText(name); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java index 895e40eee17c..da16e07c3660 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ProceedTests.java @@ -162,13 +162,13 @@ public Object capitalize(ProceedingJoinPoint pjp, String value) throws Throwable public Object doubleOrQuits(ProceedingJoinPoint pjp) throws Throwable { int value = ((Integer) pjp.getArgs()[0]).intValue(); - pjp.getArgs()[0] = new Integer(value * 2); + pjp.getArgs()[0] = Integer.valueOf(value * 2); return pjp.proceed(); } public Object addOne(ProceedingJoinPoint pjp, Float value) throws Throwable { float fv = value.floatValue(); - return pjp.proceed(new Object[] {new Float(fv + 1.0F)}); + return pjp.proceed(new Object[] {Float.valueOf(fv + 1.0F)}); } public void captureStringArgument(JoinPoint tjp, String arg) { diff --git a/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java b/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java index cd1e71a12d57..c493f075b1ae 100644 --- a/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java @@ -79,7 +79,7 @@ * @author Stephane Nicoll * @author Juergen Hoeller */ -public class AnnotationDrivenEventListenerTests { +class AnnotationDrivenEventListenerTests { private ConfigurableApplicationContext context; @@ -97,7 +97,7 @@ public void closeContext() { @Test - public void simpleEventJavaConfig() { + void simpleEventJavaConfig() { load(TestEventListener.class); TestEvent event = new TestEvent(this, "test"); TestEventListener listener = this.context.getBean(TestEventListener.class); @@ -120,7 +120,7 @@ public void simpleEventJavaConfig() { } @Test - public void simpleEventXmlConfig() { + void simpleEventXmlConfig() { this.context = new ClassPathXmlApplicationContext( "org/springframework/context/event/simple-event-configuration.xml"); @@ -141,7 +141,7 @@ public void simpleEventXmlConfig() { } @Test - public void metaAnnotationIsDiscovered() { + void metaAnnotationIsDiscovered() { load(MetaAnnotationListenerTestBean.class); MetaAnnotationListenerTestBean bean = this.context.getBean(MetaAnnotationListenerTestBean.class); this.eventCollector.assertNoEventReceived(bean); @@ -159,7 +159,7 @@ public void metaAnnotationIsDiscovered() { } @Test - public void contextEventsAreReceived() { + void contextEventsAreReceived() { load(ContextEventListener.class); ContextEventListener listener = this.context.getBean(ContextEventListener.class); @@ -175,7 +175,7 @@ public void contextEventsAreReceived() { } @Test - public void methodSignatureNoEvent() { + void methodSignatureNoEvent() { @SuppressWarnings("resource") AnnotationConfigApplicationContext failingContext = new AnnotationConfigApplicationContext(); @@ -189,7 +189,7 @@ public void methodSignatureNoEvent() { } @Test - public void simpleReply() { + void simpleReply() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, "dummy"); ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -204,7 +204,7 @@ public void simpleReply() { } @Test - public void nullReplyIgnored() { + void nullReplyIgnored() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, null); // No response ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -219,7 +219,7 @@ public void nullReplyIgnored() { } @Test - public void arrayReply() { + void arrayReply() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, new String[]{"first", "second"}); ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -234,7 +234,7 @@ public void arrayReply() { } @Test - public void collectionReply() { + void collectionReply() { load(TestEventListener.class, ReplyEventListener.class); Set replies = new LinkedHashSet<>(); replies.add("first"); @@ -253,7 +253,7 @@ public void collectionReply() { } @Test - public void collectionReplyNullValue() { + void collectionReplyNullValue() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, Arrays.asList(null, "test")); ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -268,7 +268,7 @@ public void collectionReplyNullValue() { } @Test - public void listenableFutureReply() { + void listenableFutureReply() { load(TestEventListener.class, ReplyEventListener.class); SettableListenableFuture future = new SettableListenableFuture<>(); future.set("dummy"); @@ -285,7 +285,7 @@ public void listenableFutureReply() { } @Test - public void completableFutureReply() { + void completableFutureReply() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, CompletableFuture.completedFuture("dummy")); ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -300,7 +300,7 @@ public void completableFutureReply() { } @Test - public void monoReply() { + void monoReply() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, Mono.just("dummy")); ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -315,7 +315,7 @@ public void monoReply() { } @Test - public void fluxReply() { + void fluxReply() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, Flux.just("dummy1", "dummy2")); ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -330,7 +330,7 @@ public void fluxReply() { } @Test - public void eventListenerWorksWithSimpleInterfaceProxy() { + void eventListenerWorksWithSimpleInterfaceProxy() { load(ScopedProxyTestBean.class); SimpleService proxy = this.context.getBean(SimpleService.class); @@ -347,7 +347,7 @@ public void eventListenerWorksWithSimpleInterfaceProxy() { } @Test - public void eventListenerWorksWithAnnotatedInterfaceProxy() { + void eventListenerWorksWithAnnotatedInterfaceProxy() { load(AnnotatedProxyTestBean.class); AnnotatedSimpleService proxy = this.context.getBean(AnnotatedSimpleService.class); @@ -364,7 +364,7 @@ public void eventListenerWorksWithAnnotatedInterfaceProxy() { } @Test - public void eventListenerWorksWithCglibProxy() { + void eventListenerWorksWithCglibProxy() { load(CglibProxyTestBean.class); CglibProxyTestBean proxy = this.context.getBean(CglibProxyTestBean.class); @@ -381,14 +381,14 @@ public void eventListenerWorksWithCglibProxy() { } @Test - public void privateMethodOnCglibProxyFails() { + void privateMethodOnCglibProxyFails() { assertThatExceptionOfType(BeanInitializationException.class).isThrownBy(() -> load(CglibProxyWithPrivateMethod.class)) .withCauseInstanceOf(IllegalStateException.class); } @Test - public void eventListenerWorksWithCustomScope() { + void eventListenerWorksWithCustomScope() { load(CustomScopeTestBean.class); CustomScope customScope = new CustomScope(); this.context.getBeanFactory().registerScope("custom", customScope); @@ -417,7 +417,7 @@ public void eventListenerWorksWithCustomScope() { } @Test - public void asyncProcessingApplied() throws InterruptedException { + void asyncProcessingApplied() throws InterruptedException { loadAsync(AsyncEventListener.class); String threadName = Thread.currentThread().getName(); @@ -432,7 +432,7 @@ public void asyncProcessingApplied() throws InterruptedException { } @Test - public void asyncProcessingAppliedWithInterfaceProxy() throws InterruptedException { + void asyncProcessingAppliedWithInterfaceProxy() throws InterruptedException { doLoad(AsyncConfigurationWithInterfaces.class, SimpleProxyTestBean.class); String threadName = Thread.currentThread().getName(); @@ -447,7 +447,7 @@ public void asyncProcessingAppliedWithInterfaceProxy() throws InterruptedExcepti } @Test - public void asyncProcessingAppliedWithScopedProxy() throws InterruptedException { + void asyncProcessingAppliedWithScopedProxy() throws InterruptedException { doLoad(AsyncConfigurationWithInterfaces.class, ScopedProxyTestBean.class); String threadName = Thread.currentThread().getName(); @@ -462,7 +462,7 @@ public void asyncProcessingAppliedWithScopedProxy() throws InterruptedException } @Test - public void exceptionPropagated() { + void exceptionPropagated() { load(ExceptionEventListener.class); TestEvent event = new TestEvent(this, "fail"); ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class); @@ -475,7 +475,7 @@ public void exceptionPropagated() { } @Test - public void exceptionNotPropagatedWithAsync() throws InterruptedException { + void exceptionNotPropagatedWithAsync() throws InterruptedException { loadAsync(ExceptionEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, "fail"); ExceptionEventListener listener = this.context.getBean(ExceptionEventListener.class); @@ -489,7 +489,7 @@ public void exceptionNotPropagatedWithAsync() throws InterruptedException { } @Test - public void listenerWithSimplePayload() { + void listenerWithSimplePayload() { load(TestEventListener.class); TestEventListener listener = this.context.getBean(TestEventListener.class); @@ -500,7 +500,7 @@ public void listenerWithSimplePayload() { } @Test - public void listenerWithNonMatchingPayload() { + void listenerWithNonMatchingPayload() { load(TestEventListener.class); TestEventListener listener = this.context.getBean(TestEventListener.class); @@ -511,7 +511,7 @@ public void listenerWithNonMatchingPayload() { } @Test - public void replyWithPayload() { + void replyWithPayload() { load(TestEventListener.class, ReplyEventListener.class); AnotherTestEvent event = new AnotherTestEvent(this, "String"); ReplyEventListener replyEventListener = this.context.getBean(ReplyEventListener.class); @@ -527,7 +527,7 @@ public void replyWithPayload() { } @Test - public void listenerWithGenericApplicationEvent() { + void listenerWithGenericApplicationEvent() { load(GenericEventListener.class); GenericEventListener listener = this.context.getBean(GenericEventListener.class); @@ -538,7 +538,7 @@ public void listenerWithGenericApplicationEvent() { } @Test - public void listenerWithResolvableTypeEvent() { + void listenerWithResolvableTypeEvent() { load(ResolvableTypeEventListener.class); ResolvableTypeEventListener listener = this.context.getBean(ResolvableTypeEventListener.class); @@ -550,7 +550,7 @@ public void listenerWithResolvableTypeEvent() { } @Test - public void listenerWithResolvableTypeEventWrongGeneric() { + void listenerWithResolvableTypeEventWrongGeneric() { load(ResolvableTypeEventListener.class); ResolvableTypeEventListener listener = this.context.getBean(ResolvableTypeEventListener.class); @@ -562,12 +562,12 @@ public void listenerWithResolvableTypeEventWrongGeneric() { } @Test - public void conditionMatch() { + void conditionMatch() { validateConditionMatch(ConditionalEventListener.class); } @Test - public void conditionMatchWithProxy() { + void conditionMatchWithProxy() { validateConditionMatch(ConditionalEventListener.class, MethodValidationPostProcessor.class); } @@ -600,7 +600,7 @@ private void validateConditionMatch(Class... classes) { } @Test - public void conditionDoesNotMatch() { + void conditionDoesNotMatch() { long maxLong = Long.MAX_VALUE; load(ConditionalEventListener.class); TestEvent event = new TestEvent(this, "KO"); @@ -625,7 +625,7 @@ public void conditionDoesNotMatch() { } @Test - public void orderedListeners() { + void orderedListeners() { load(OrderedTestListener.class); OrderedTestListener listener = this.context.getBean(OrderedTestListener.class); @@ -635,7 +635,7 @@ public void orderedListeners() { } @Test @Disabled // SPR-15122 - public void listenersReceiveEarlyEvents() { + void listenersReceiveEarlyEvents() { load(EventOnPostConstruct.class, OrderedTestListener.class); OrderedTestListener listener = this.context.getBean(OrderedTestListener.class); @@ -643,7 +643,7 @@ public void listenersReceiveEarlyEvents() { } @Test - public void missingListenerBeanIgnored() { + void missingListenerBeanIgnored() { load(MissingEventListener.class); context.getBean(UseMissingEventListener.class); context.getBean(ApplicationEventMulticaster.class).multicastEvent(new TestEvent(this)); @@ -697,7 +697,7 @@ public TestConditionEvaluator conditionEvaluator() { static class TestConditionEvaluator { public boolean valid(Double ratio) { - return new Double(42).equals(ratio); + return Double.valueOf(42).equals(ratio); } } } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java index adff3bb372d3..988e068a0b1b 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -341,10 +341,10 @@ void testWithExposeClassLoader() throws Exception { assertIsRegistered("Bean instance not registered", objectName); - Object result = server.invoke(objectName, "add", new Object[] {new Integer(2), new Integer(3)}, new String[] { + Object result = server.invoke(objectName, "add", new Object[] {2, 3}, new String[] { int.class.getName(), int.class.getName()}); - assertThat(new Integer(5)).as("Incorrect result return from add").isEqualTo(result); + assertThat(Integer.valueOf(5)).as("Incorrect result return from add").isEqualTo(result); assertThat(server.getAttribute(objectName, "Name")).as("Incorrect attribute value").isEqualTo(name); server.setAttribute(objectName, new Attribute("Name", otherName)); @@ -352,7 +352,7 @@ void testWithExposeClassLoader() throws Exception { } @Test - void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() throws Exception { + void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("^&_invalidObjectName_(*", builder.getBeanDefinition()); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java index 26a8b0defffa..c754af69ca15 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -60,7 +60,7 @@ public void testRegisterOperations() throws Exception { IJmxTestBean bean = getBean(); assertThat(bean).isNotNull(); MBeanInfo inf = getMBeanInfo(); - assertThat(inf.getOperations().length).as("Incorrect number of operations registered").isEqualTo(getExpectedOperationCount()); + assertThat(inf.getOperations()).as("Incorrect number of operations registered").hasSize(getExpectedOperationCount()); } @Test @@ -68,7 +68,7 @@ public void testRegisterAttributes() throws Exception { IJmxTestBean bean = getBean(); assertThat(bean).isNotNull(); MBeanInfo inf = getMBeanInfo(); - assertThat(inf.getAttributes().length).as("Incorrect number of attributes registered").isEqualTo(getExpectedAttributeCount()); + assertThat(inf.getAttributes()).as("Incorrect number of attributes registered").hasSize(getExpectedAttributeCount()); } @Test @@ -81,7 +81,7 @@ public void testGetMBeanInfo() throws Exception { public void testGetMBeanAttributeInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanAttributeInfo[] inf = info.getAttributes(); - assertThat(inf.length).as("Invalid number of Attributes returned").isEqualTo(getExpectedAttributeCount()); + assertThat(inf).as("Invalid number of Attributes returned").hasSize(getExpectedAttributeCount()); for (int x = 0; x < inf.length; x++) { assertThat(inf[x]).as("MBeanAttributeInfo should not be null").isNotNull(); @@ -93,7 +93,7 @@ public void testGetMBeanAttributeInfo() throws Exception { public void testGetMBeanOperationInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanOperationInfo[] inf = info.getOperations(); - assertThat(inf.length).as("Invalid number of Operations returned").isEqualTo(getExpectedOperationCount()); + assertThat(inf).as("Invalid number of Operations returned").hasSize(getExpectedOperationCount()); for (int x = 0; x < inf.length; x++) { assertThat(inf[x]).as("MBeanOperationInfo should not be null").isNotNull(); @@ -128,8 +128,8 @@ public void testGetAttribute() throws Exception { public void testOperationInvocation() throws Exception{ ObjectName objectName = ObjectNameManager.getInstance(getObjectName()); Object result = getServer().invoke(objectName, "add", - new Object[] {new Integer(20), new Integer(30)}, new String[] {"int", "int"}); - assertThat(result).as("Incorrect result").isEqualTo(new Integer(50)); + new Object[] {20, 30}, new String[] {"int", "int"}); + assertThat(result).as("Incorrect result").isEqualTo(50); } @Test @@ -150,12 +150,12 @@ public void testAttributeHasCorrespondingOperations() throws Exception { ModelMBeanOperationInfo get = info.getOperation("getName"); assertThat(get).as("get operation should not be null").isNotNull(); - assertThat(new Integer(4)).as("get operation should have visibility of four").isEqualTo(get.getDescriptor().getFieldValue("visibility")); + assertThat(Integer.valueOf(4)).as("get operation should have visibility of four").isEqualTo(get.getDescriptor().getFieldValue("visibility")); assertThat(get.getDescriptor().getFieldValue("role")).as("get operation should have role \"getter\"").isEqualTo("getter"); ModelMBeanOperationInfo set = info.getOperation("setName"); assertThat(set).as("set operation should not be null").isNotNull(); - assertThat(new Integer(4)).as("set operation should have visibility of four").isEqualTo(set.getDescriptor().getFieldValue("visibility")); + assertThat(Integer.valueOf(4)).as("set operation should have visibility of four").isEqualTo(set.getDescriptor().getFieldValue("visibility")); assertThat(set.getDescriptor().getFieldValue("role")).as("set operation should have role \"setter\"").isEqualTo("setter"); } @@ -163,12 +163,12 @@ public void testAttributeHasCorrespondingOperations() throws Exception { public void testNotificationMetadata() throws Exception { ModelMBeanInfo info = (ModelMBeanInfo) getMBeanInfo(); MBeanNotificationInfo[] notifications = info.getNotifications(); - assertThat(notifications.length).as("Incorrect number of notifications").isEqualTo(1); + assertThat(notifications).as("Incorrect number of notifications").hasSize(1); assertThat(notifications[0].getName()).as("Incorrect notification name").isEqualTo("My Notification"); String[] notifTypes = notifications[0].getNotifTypes(); - assertThat(notifTypes.length).as("Incorrect number of notification types").isEqualTo(2); + assertThat(notifTypes).as("Incorrect number of notification types").hasSize(2); assertThat(notifTypes[0]).as("Notification type.foo not found").isEqualTo("type.foo"); assertThat(notifTypes[1]).as("Notification type.bar not found").isEqualTo("type.bar"); } diff --git a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java index 16253239fa74..d6702d317db7 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -41,7 +41,7 @@ * @author Chris Beams */ @EnabledForTestGroups(LONG_RUNNING) -public class ScriptFactoryPostProcessorTests { +class ScriptFactoryPostProcessorTests { private static final String MESSAGE_TEXT = "Bingo"; @@ -79,18 +79,18 @@ public class ScriptFactoryPostProcessorTests { @Test - public void testDoesNothingWhenPostProcessingNonScriptFactoryTypeBeforeInstantiation() throws Exception { + void testDoesNothingWhenPostProcessingNonScriptFactoryTypeBeforeInstantiation() { assertThat(new ScriptFactoryPostProcessor().postProcessBeforeInstantiation(getClass(), "a.bean")).isNull(); } @Test - public void testThrowsExceptionIfGivenNonAbstractBeanFactoryImplementation() throws Exception { + void testThrowsExceptionIfGivenNonAbstractBeanFactoryImplementation() { assertThatIllegalStateException().isThrownBy(() -> new ScriptFactoryPostProcessor().setBeanFactory(mock(BeanFactory.class))); } @Test - public void testChangeScriptWithRefreshableBeanFunctionality() throws Exception { + void testChangeScriptWithRefreshableBeanFunctionality() throws Exception { BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(true); BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean(); @@ -111,7 +111,7 @@ public void testChangeScriptWithRefreshableBeanFunctionality() throws Exception } @Test - public void testChangeScriptWithNoRefreshableBeanFunctionality() throws Exception { + void testChangeScriptWithNoRefreshableBeanFunctionality() throws Exception { BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(false); BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean(); @@ -131,7 +131,7 @@ public void testChangeScriptWithNoRefreshableBeanFunctionality() throws Exceptio } @Test - public void testRefreshedScriptReferencePropagatesToCollaborators() throws Exception { + void testRefreshedScriptReferencePropagatesToCollaborators() throws Exception { BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(true); BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean(); BeanDefinitionBuilder collaboratorBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultMessengerService.class); @@ -159,7 +159,7 @@ public void testRefreshedScriptReferencePropagatesToCollaborators() throws Excep } @Test - public void testReferencesAcrossAContainerHierarchy() throws Exception { + void testReferencesAcrossAContainerHierarchy() throws Exception { GenericApplicationContext businessContext = new GenericApplicationContext(); businessContext.registerBeanDefinition("messenger", BeanDefinitionBuilder.rootBeanDefinition(StubMessenger.class).getBeanDefinition()); businessContext.refresh(); @@ -175,13 +175,13 @@ public void testReferencesAcrossAContainerHierarchy() throws Exception { } @Test - public void testScriptHavingAReferenceToAnotherBean() throws Exception { + void testScriptHavingAReferenceToAnotherBean() throws Exception { // just tests that the (singleton) script-backed bean is able to be instantiated with references to its collaborators new ClassPathXmlApplicationContext("org/springframework/scripting/support/groovyReferences.xml"); } @Test - public void testForRefreshedScriptHavingErrorPickedUpOnFirstCall() throws Exception { + void testForRefreshedScriptHavingErrorPickedUpOnFirstCall() throws Exception { BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(true); BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean(); BeanDefinitionBuilder collaboratorBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultMessengerService.class); @@ -202,13 +202,12 @@ public void testForRefreshedScriptHavingErrorPickedUpOnFirstCall() throws Except // needs The Sundays compiler; must NOT throw any exception here... source.setScript("I keep hoping you are the same as me, and I'll send you letters and come to your house for tea"); Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME); - assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> - refreshedMessenger.getMessage()) + assertThatExceptionOfType(FatalBeanException.class).isThrownBy(refreshedMessenger::getMessage) .matches(ex -> ex.contains(ScriptCompilationException.class)); } @Test - public void testPrototypeScriptedBean() throws Exception { + void testPrototypeScriptedBean() throws Exception { GenericApplicationContext ctx = new GenericApplicationContext(); ctx.registerBeanDefinition("messenger", BeanDefinitionBuilder.rootBeanDefinition(StubMessenger.class).getBeanDefinition()); @@ -236,7 +235,7 @@ private static StaticScriptSource getScriptSource(GenericApplicationContext ctx) private static BeanDefinition createScriptFactoryPostProcessor(boolean isRefreshable) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ScriptFactoryPostProcessor.class); if (isRefreshable) { - builder.addPropertyValue("defaultRefreshCheckDelay", new Long(1)); + builder.addPropertyValue("defaultRefreshCheckDelay", 1L); } return builder.getBeanDefinition(); } diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java index 602454760041..f8ffc26ab8ad 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -36,17 +36,17 @@ * @author Stephane Nicoll * @since 07.03.2006 */ -public class DataBinderFieldAccessTests { +class DataBinderFieldAccessTests { @Test - public void bindingNoErrors() throws Exception { + void bindingNoErrors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); assertThat(binder.isIgnoreUnknownFields()).isTrue(); binder.initDirectFieldAccess(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "Rod")); - pvs.addPropertyValue(new PropertyValue("age", new Integer(32))); + pvs.addPropertyValue(new PropertyValue("age", 32)); pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue")); binder.bind(pvs); @@ -62,21 +62,21 @@ public void bindingNoErrors() throws Exception { } @Test - public void bindingNoErrorsNotIgnoreUnknown() throws Exception { + void bindingNoErrorsNotIgnoreUnknown() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); binder.initDirectFieldAccess(); binder.setIgnoreUnknownFields(false); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "Rod")); - pvs.addPropertyValue(new PropertyValue("age", new Integer(32))); + pvs.addPropertyValue(new PropertyValue("age", 32)); pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue")); assertThatExceptionOfType(NotWritablePropertyException.class).isThrownBy(() -> binder.bind(pvs)); } @Test - public void bindingWithErrors() throws Exception { + void bindingWithErrors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); binder.initDirectFieldAccess(); @@ -105,7 +105,7 @@ public void bindingWithErrors() throws Exception { } @Test - public void nestedBindingWithDefaultConversionNoErrors() throws Exception { + void nestedBindingWithDefaultConversionNoErrors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); assertThat(binder.isIgnoreUnknownFields()).isTrue(); @@ -122,7 +122,7 @@ public void nestedBindingWithDefaultConversionNoErrors() throws Exception { } @Test - public void nestedBindingWithDisabledAutoGrow() throws Exception { + void nestedBindingWithDisabledAutoGrow() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); binder.setAutoGrowNestedPaths(false); @@ -135,7 +135,7 @@ public void nestedBindingWithDisabledAutoGrow() throws Exception { } @Test - public void bindingWithErrorsAndCustomEditors() throws Exception { + void bindingWithErrorsAndCustomEditors() throws Exception { FieldAccessBean rod = new FieldAccessBean(); DataBinder binder = new DataBinder(rod, "person"); binder.initDirectFieldAccess(); diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java index 420e17d9a3fa..a820d40a6a43 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -77,10 +77,10 @@ * @author Rob Harrop * @author Kazuki Shimizu */ -public class DataBinderTests { +class DataBinderTests { @Test - public void testBindingNoErrors() throws BindException { + void testBindingNoErrors() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); assertThat(binder.isIgnoreUnknownFields()).isTrue(); @@ -115,7 +115,7 @@ public void testBindingNoErrors() throws BindException { } @Test - public void testBindingWithDefaultConversionNoErrors() throws BindException { + void testBindingWithDefaultConversionNoErrors() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); assertThat(binder.isIgnoreUnknownFields()).isTrue(); @@ -131,7 +131,7 @@ public void testBindingWithDefaultConversionNoErrors() throws BindException { } @Test - public void testNestedBindingWithDefaultConversionNoErrors() throws BindException { + void testNestedBindingWithDefaultConversionNoErrors() throws BindException { TestBean rod = new TestBean(new TestBean()); DataBinder binder = new DataBinder(rod, "person"); assertThat(binder.isIgnoreUnknownFields()).isTrue(); @@ -147,7 +147,7 @@ public void testNestedBindingWithDefaultConversionNoErrors() throws BindExceptio } @Test - public void testBindingNoErrorsNotIgnoreUnknown() { + void testBindingNoErrorsNotIgnoreUnknown() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); binder.setIgnoreUnknownFields(false); @@ -160,7 +160,7 @@ public void testBindingNoErrorsNotIgnoreUnknown() { } @Test - public void testBindingNoErrorsWithInvalidField() { + void testBindingNoErrorsWithInvalidField() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -171,7 +171,7 @@ public void testBindingNoErrorsWithInvalidField() { } @Test - public void testBindingNoErrorsWithIgnoreInvalid() { + void testBindingNoErrorsWithIgnoreInvalid() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); binder.setIgnoreInvalidFields(true); @@ -183,7 +183,7 @@ public void testBindingNoErrorsWithIgnoreInvalid() { } @Test - public void testBindingWithErrors() { + void testBindingWithErrors() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -245,7 +245,7 @@ public void testBindingWithErrors() { } @Test - public void testBindingWithSystemFieldError() { + void testBindingWithSystemFieldError() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -257,7 +257,7 @@ public void testBindingWithSystemFieldError() { } @Test - public void testBindingWithErrorsAndCustomEditors() { + void testBindingWithErrorsAndCustomEditors() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); binder.registerCustomEditor(String.class, "touchy", new PropertyEditorSupport() { @@ -325,7 +325,7 @@ public String getAsText() { } @Test - public void testBindingWithCustomEditorOnObjectField() { + void testBindingWithCustomEditorOnObjectField() { BeanWithObjectProperty tb = new BeanWithObjectProperty(); DataBinder binder = new DataBinder(tb); binder.registerCustomEditor(Integer.class, "object", new CustomNumberEditor(Integer.class, true)); @@ -336,7 +336,7 @@ public void testBindingWithCustomEditorOnObjectField() { } @Test - public void testBindingWithFormatter() { + void testBindingWithFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); @@ -349,18 +349,18 @@ public void testBindingWithFormatter() { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2)); + assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(1.2f)); assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2"); PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class); assertThat(editor).isNotNull(); - editor.setValue(new Float(1.4)); + editor.setValue(1.4f); assertThat(editor.getAsText()).isEqualTo("1,4"); editor = binder.getBindingResult().findEditor("myFloat", null); assertThat(editor).isNotNull(); editor.setAsText("1,6"); - assertThat(editor.getValue()).isEqualTo(new Float(1.6)); + assertThat(editor.getValue()).isEqualTo(1.6f); } finally { LocaleContextHolder.resetLocaleContext(); @@ -368,7 +368,7 @@ public void testBindingWithFormatter() { } @Test - public void testBindingErrorWithFormatter() { + void testBindingErrorWithFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); @@ -381,7 +381,7 @@ public void testBindingErrorWithFormatter() { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0)); + assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(0.0f)); assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2"); assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue(); } @@ -391,7 +391,7 @@ public void testBindingErrorWithFormatter() { } @Test - public void testBindingErrorWithParseExceptionFromFormatter() { + void testBindingErrorWithParseExceptionFromFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); @@ -419,7 +419,7 @@ public String print(String object, Locale locale) { } @Test - public void testBindingErrorWithRuntimeExceptionFromFormatter() { + void testBindingErrorWithRuntimeExceptionFromFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); @@ -447,7 +447,7 @@ public String print(String object, Locale locale) { } @Test - public void testBindingWithFormatterAgainstList() { + void testBindingWithFormatterAgainstList() { BeanWithIntegerList tb = new BeanWithIntegerList(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); @@ -469,7 +469,7 @@ public void testBindingWithFormatterAgainstList() { } @Test - public void testBindingErrorWithFormatterAgainstList() { + void testBindingErrorWithFormatterAgainstList() { BeanWithIntegerList tb = new BeanWithIntegerList(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); @@ -492,7 +492,7 @@ public void testBindingErrorWithFormatterAgainstList() { } @Test - public void testBindingWithFormatterAgainstFields() { + void testBindingWithFormatterAgainstFields() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); @@ -506,18 +506,18 @@ public void testBindingWithFormatterAgainstFields() { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2)); + assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(1.2f)); assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2"); PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class); assertThat(editor).isNotNull(); - editor.setValue(new Float(1.4)); + editor.setValue(1.4f); assertThat(editor.getAsText()).isEqualTo("1,4"); editor = binder.getBindingResult().findEditor("myFloat", null); assertThat(editor).isNotNull(); editor.setAsText("1,6"); - assertThat(editor.getValue()).isEqualTo(new Float(1.6)); + assertThat(editor.getValue()).isEqualTo(1.6f); } finally { LocaleContextHolder.resetLocaleContext(); @@ -525,7 +525,7 @@ public void testBindingWithFormatterAgainstFields() { } @Test - public void testBindingErrorWithFormatterAgainstFields() { + void testBindingErrorWithFormatterAgainstFields() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); binder.initDirectFieldAccess(); @@ -539,7 +539,7 @@ public void testBindingErrorWithFormatterAgainstFields() { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0)); + assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(0.0f)); assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2"); assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue(); } @@ -549,7 +549,7 @@ public void testBindingErrorWithFormatterAgainstFields() { } @Test - public void testBindingWithCustomFormatter() { + void testBindingWithCustomFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); binder.addCustomFormatter(new NumberStyleFormatter(), Float.class); @@ -559,12 +559,12 @@ public void testBindingWithCustomFormatter() { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertThat(tb.getMyFloat()).isEqualTo(new Float(1.2)); + assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(1.2f)); assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1,2"); PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class); assertThat(editor).isNotNull(); - editor.setValue(new Float(1.4)); + editor.setValue(1.4f); assertThat(editor.getAsText()).isEqualTo("1,4"); editor = binder.getBindingResult().findEditor("myFloat", null); @@ -578,7 +578,7 @@ public void testBindingWithCustomFormatter() { } @Test - public void testBindingErrorWithCustomFormatter() { + void testBindingErrorWithCustomFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); binder.addCustomFormatter(new NumberStyleFormatter()); @@ -588,7 +588,7 @@ public void testBindingErrorWithCustomFormatter() { LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); - assertThat(tb.getMyFloat()).isEqualTo(new Float(0.0)); + assertThat(tb.getMyFloat()).isEqualTo(Float.valueOf(0.0f)); assertThat(binder.getBindingResult().getFieldValue("myFloat")).isEqualTo("1x2"); assertThat(binder.getBindingResult().hasFieldErrors("myFloat")).isTrue(); assertThat(binder.getBindingResult().getFieldError("myFloat").getCode()).isEqualTo("typeMismatch"); @@ -599,7 +599,7 @@ public void testBindingErrorWithCustomFormatter() { } @Test - public void testBindingErrorWithParseExceptionFromCustomFormatter() { + void testBindingErrorWithParseExceptionFromCustomFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); @@ -624,7 +624,7 @@ public String print(String object, Locale locale) { } @Test - public void testBindingErrorWithRuntimeExceptionFromCustomFormatter() { + void testBindingErrorWithRuntimeExceptionFromCustomFormatter() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb); @@ -649,7 +649,7 @@ public String print(String object, Locale locale) { } @Test - public void testConversionWithInappropriateStringEditor() { + void testConversionWithInappropriateStringEditor() { DataBinder dataBinder = new DataBinder(null); DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(); dataBinder.setConversionService(conversionService); @@ -662,7 +662,7 @@ public void testConversionWithInappropriateStringEditor() { } @Test - public void testBindingWithAllowedFields() throws BindException { + void testBindingWithAllowedFields() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod); binder.setAllowedFields("name", "myparam"); @@ -677,7 +677,7 @@ public void testBindingWithAllowedFields() throws BindException { } @Test - public void testBindingWithDisallowedFields() throws BindException { + void testBindingWithDisallowedFields() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod); binder.setDisallowedFields("age"); @@ -695,7 +695,7 @@ public void testBindingWithDisallowedFields() throws BindException { } @Test - public void testBindingWithAllowedAndDisallowedFields() throws BindException { + void testBindingWithAllowedAndDisallowedFields() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod); binder.setAllowedFields("name", "myparam"); @@ -709,12 +709,12 @@ public void testBindingWithAllowedAndDisallowedFields() throws BindException { assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); assertThat(rod.getAge() == 0).as("did not change age").isTrue(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields).hasSize(1); assertThat(disallowedFields[0]).isEqualTo("age"); } @Test - public void testBindingWithOverlappingAllowedAndDisallowedFields() throws BindException { + void testBindingWithOverlappingAllowedAndDisallowedFields() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod); binder.setAllowedFields("name", "age"); @@ -728,12 +728,12 @@ public void testBindingWithOverlappingAllowedAndDisallowedFields() throws BindEx assertThat(rod.getName().equals("Rod")).as("changed name correctly").isTrue(); assertThat(rod.getAge() == 0).as("did not change age").isTrue(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields).hasSize(1); assertThat(disallowedFields[0]).isEqualTo("age"); } @Test - public void testBindingWithAllowedFieldsUsingAsterisks() throws BindException { + void testBindingWithAllowedFieldsUsingAsterisks() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); binder.setAllowedFields("nam*", "*ouchy"); @@ -750,7 +750,7 @@ public void testBindingWithAllowedFieldsUsingAsterisks() throws BindException { assertThat("Rod".equals(rod.getTouchy())).as("changed touchy correctly").isTrue(); assertThat(rod.getAge() == 0).as("did not change age").isTrue(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields).hasSize(1); assertThat(disallowedFields[0]).isEqualTo("age"); Map m = binder.getBindingResult().getModel(); @@ -760,7 +760,7 @@ public void testBindingWithAllowedFieldsUsingAsterisks() throws BindException { } @Test - public void testBindingWithAllowedAndDisallowedMapFields() throws BindException { + void testBindingWithAllowedAndDisallowedMapFields() throws BindException { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod); binder.setAllowedFields("someMap[key1]", "someMap[key2]"); @@ -779,7 +779,7 @@ public void testBindingWithAllowedAndDisallowedMapFields() throws BindException assertThat(rod.getSomeMap().get("key3")).isNull(); assertThat(rod.getSomeMap().get("key4")).isNull(); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertThat(disallowedFields.length).isEqualTo(2); + assertThat(disallowedFields).hasSize(2); assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key3]")).isTrue(); assertThat(ObjectUtils.containsElement(disallowedFields, "someMap[key4]")).isTrue(); } @@ -788,7 +788,7 @@ public void testBindingWithAllowedAndDisallowedMapFields() throws BindException * Tests for required field, both null, non-existing and empty strings. */ @Test - public void testBindingWithRequiredFields() { + void testBindingWithRequiredFields() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); @@ -819,7 +819,7 @@ public void testBindingWithRequiredFields() { } @Test - public void testBindingWithRequiredMapFields() { + void testBindingWithRequiredMapFields() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); @@ -839,7 +839,7 @@ public void testBindingWithRequiredMapFields() { } @Test - public void testBindingWithNestedObjectCreation() { + void testBindingWithNestedObjectCreation() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "person"); @@ -860,7 +860,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testCustomEditorWithOldValueAccess() { + void testCustomEditorWithOldValueAccess() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "tb"); @@ -885,7 +885,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testCustomEditorForSingleProperty() { + void testCustomEditorForSingleProperty() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); DataBinder binder = new DataBinder(tb, "tb"); @@ -925,7 +925,7 @@ public String getAsText() { } @Test - public void testCustomEditorForPrimitiveProperty() { + void testCustomEditorForPrimitiveProperty() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "tb"); @@ -949,7 +949,7 @@ public String getAsText() { } @Test - public void testCustomEditorForAllStringProperties() { + void testCustomEditorForAllStringProperties() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "tb"); @@ -981,7 +981,7 @@ public String getAsText() { } @Test - public void testCustomFormatterForSingleProperty() { + void testCustomFormatterForSingleProperty() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); DataBinder binder = new DataBinder(tb, "tb"); @@ -1021,7 +1021,7 @@ public String print(String object, Locale locale) { } @Test - public void testCustomFormatterForPrimitiveProperty() { + void testCustomFormatterForPrimitiveProperty() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "tb"); @@ -1045,7 +1045,7 @@ public String print(Integer object, Locale locale) { } @Test - public void testCustomFormatterForAllStringProperties() { + void testCustomFormatterForAllStringProperties() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "tb"); @@ -1077,7 +1077,7 @@ public String print(String object, Locale locale) { } @Test - public void testJavaBeanPropertyConventions() { + void testJavaBeanPropertyConventions() { Book book = new Book(); DataBinder binder = new DataBinder(book); @@ -1101,7 +1101,7 @@ public void testJavaBeanPropertyConventions() { } @Test - public void testOptionalProperty() { + void testOptionalProperty() { OptionalHolder bean = new OptionalHolder(); DataBinder binder = new DataBinder(bean); binder.setConversionService(new DefaultConversionService()); @@ -1111,7 +1111,7 @@ public void testOptionalProperty() { pvs.add("name", null); binder.bind(pvs); assertThat(bean.getId()).isEqualTo("1"); - assertThat(bean.getName().isPresent()).isFalse(); + assertThat(bean.getName()).isEmpty(); pvs = new MutablePropertyValues(); pvs.add("id", "2"); @@ -1122,7 +1122,7 @@ public void testOptionalProperty() { } @Test - public void testValidatorNoErrors() throws Exception { + void testValidatorNoErrors() throws Exception { TestBean tb = new TestBean(); tb.setAge(33); tb.setName("Rod"); @@ -1183,7 +1183,7 @@ public void testValidatorNoErrors() throws Exception { } @Test - public void testValidatorWithErrors() { + void testValidatorWithErrors() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); @@ -1252,7 +1252,7 @@ public void testValidatorWithErrors() { } @Test - public void testValidatorWithErrorsAndCodesPrefix() { + void testValidatorWithErrorsAndCodesPrefix() { TestBean tb = new TestBean(); tb.setSpouse(new TestBean()); @@ -1324,7 +1324,7 @@ public void testValidatorWithErrorsAndCodesPrefix() { } @Test - public void testValidatorWithNestedObjectNull() { + void testValidatorWithNestedObjectNull() { TestBean tb = new TestBean(); Errors errors = new BeanPropertyBindingResult(tb, "tb"); Validator testValidator = new TestBeanValidator(); @@ -1343,7 +1343,7 @@ public void testValidatorWithNestedObjectNull() { } @Test - public void testNestedValidatorWithoutNestedPath() { + void testNestedValidatorWithoutNestedPath() { TestBean tb = new TestBean(); tb.setName("XXX"); Errors errors = new BeanPropertyBindingResult(tb, "tb"); @@ -1357,13 +1357,13 @@ public void testNestedValidatorWithoutNestedPath() { } @Test - public void testBindingStringArrayToIntegerSet() { + void testBindingStringArrayToIntegerSet() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(Set.class, new CustomCollectionEditor(TreeSet.class) { @Override protected Object convertElement(Object element) { - return new Integer(element.toString()); + return Integer.valueOf(element.toString()); } }); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -1386,7 +1386,7 @@ protected Object convertElement(Object element) { } @Test - public void testBindingNullToEmptyCollection() { + void testBindingNullToEmptyCollection() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(Set.class, new CustomCollectionEditor(TreeSet.class, true)); @@ -1400,7 +1400,7 @@ public void testBindingNullToEmptyCollection() { } @Test - public void testBindingToIndexedField() { + void testBindingToIndexedField() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(String.class, "array.name", new PropertyEditorSupport() { @@ -1439,7 +1439,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testBindingToNestedIndexedField() { + void testBindingToNestedIndexedField() { IndexedTestBean tb = new IndexedTestBean(); tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean()); tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean()); @@ -1470,7 +1470,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testEditorForNestedIndexedField() { + void testEditorForNestedIndexedField() { IndexedTestBean tb = new IndexedTestBean(); tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean()); tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean()); @@ -1496,7 +1496,7 @@ public String getAsText() { } @Test - public void testSpecificEditorForNestedIndexedField() { + void testSpecificEditorForNestedIndexedField() { IndexedTestBean tb = new IndexedTestBean(); tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean()); tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean()); @@ -1522,7 +1522,7 @@ public String getAsText() { } @Test - public void testInnerSpecificEditorForNestedIndexedField() { + void testInnerSpecificEditorForNestedIndexedField() { IndexedTestBean tb = new IndexedTestBean(); tb.getArray()[0].setNestedIndexedBean(new IndexedTestBean()); tb.getArray()[1].setNestedIndexedBean(new IndexedTestBean()); @@ -1548,7 +1548,7 @@ public String getAsText() { } @Test - public void testDirectBindingToIndexedField() { + void testDirectBindingToIndexedField() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(TestBean.class, "array", new PropertyEditorSupport() { @@ -1601,7 +1601,7 @@ public String getAsText() { } @Test - public void testDirectBindingToEmptyIndexedFieldWithRegisteredSpecificEditor() { + void testDirectBindingToEmptyIndexedFieldWithRegisteredSpecificEditor() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(TestBean.class, "map[key0]", new PropertyEditorSupport() { @@ -1632,7 +1632,7 @@ public String getAsText() { } @Test - public void testDirectBindingToEmptyIndexedFieldWithRegisteredGenericEditor() { + void testDirectBindingToEmptyIndexedFieldWithRegisteredGenericEditor() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(TestBean.class, "map", new PropertyEditorSupport() { @@ -1663,7 +1663,7 @@ public String getAsText() { } @Test - public void testCustomEditorWithSubclass() { + void testCustomEditorWithSubclass() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(TestBean.class, new PropertyEditorSupport() { @@ -1697,7 +1697,7 @@ public String getAsText() { } @Test - public void testBindToStringArrayWithArrayEditor() { + void testBindToStringArrayWithArrayEditor() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(String[].class, "stringArray", new PropertyEditorSupport() { @@ -1717,7 +1717,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testBindToStringArrayWithComponentEditor() { + void testBindToStringArrayWithComponentEditor() { TestBean tb = new TestBean(); DataBinder binder = new DataBinder(tb, "tb"); binder.registerCustomEditor(String.class, "stringArray", new PropertyEditorSupport() { @@ -1737,7 +1737,7 @@ public void setAsText(String text) throws IllegalArgumentException { } @Test - public void testBindingErrors() { + void testBindingErrors() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -1764,7 +1764,7 @@ public void testBindingErrors() { } @Test - public void testAddAllErrors() { + void testAddAllErrors() { TestBean rod = new TestBean(); DataBinder binder = new DataBinder(rod, "person"); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -1784,7 +1784,7 @@ public void testAddAllErrors() { @Test @SuppressWarnings("unchecked") - public void testBindingWithResortedList() { + void testBindingWithResortedList() { IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new DataBinder(tb, "tb"); MutablePropertyValues pvs = new MutablePropertyValues(); @@ -1802,7 +1802,7 @@ public void testBindingWithResortedList() { } @Test - public void testRejectWithoutDefaultMessage() { + void testRejectWithoutDefaultMessage() { TestBean tb = new TestBean(); tb.setName("myName"); tb.setAge(99); @@ -1820,7 +1820,7 @@ public void testRejectWithoutDefaultMessage() { } @Test - public void testBindExceptionSerializable() throws Exception { + void testBindExceptionSerializable() throws Exception { SerializablePerson tb = new SerializablePerson(); tb.setName("myName"); tb.setAge(99); @@ -1849,7 +1849,7 @@ public void testBindExceptionSerializable() throws Exception { } @Test - public void testTrackDisallowedFields() { + void testTrackDisallowedFields() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.setAllowedFields("name", "age"); @@ -1864,12 +1864,12 @@ public void testTrackDisallowedFields() { assertThat(testBean.getName()).isEqualTo(name); String[] disallowedFields = binder.getBindingResult().getSuppressedFields(); - assertThat(disallowedFields.length).isEqualTo(1); + assertThat(disallowedFields).hasSize(1); assertThat(disallowedFields[0]).isEqualTo("beanName"); } @Test - public void testAutoGrowWithinDefaultLimit() { + void testAutoGrowWithinDefaultLimit() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); @@ -1877,11 +1877,11 @@ public void testAutoGrowWithinDefaultLimit() { mpvs.add("friends[4]", ""); binder.bind(mpvs); - assertThat(testBean.getFriends().size()).isEqualTo(5); + assertThat(testBean.getFriends()).hasSize(5); } @Test - public void testAutoGrowBeyondDefaultLimit() { + void testAutoGrowBeyondDefaultLimit() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); @@ -1894,7 +1894,7 @@ public void testAutoGrowBeyondDefaultLimit() { } @Test - public void testAutoGrowWithinCustomLimit() { + void testAutoGrowWithinCustomLimit() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.setAutoGrowCollectionLimit(10); @@ -1903,11 +1903,11 @@ public void testAutoGrowWithinCustomLimit() { mpvs.add("friends[4]", ""); binder.bind(mpvs); - assertThat(testBean.getFriends().size()).isEqualTo(5); + assertThat(testBean.getFriends()).hasSize(5); } @Test - public void testAutoGrowBeyondCustomLimit() { + void testAutoGrowBeyondCustomLimit() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.setAutoGrowCollectionLimit(10); @@ -1921,7 +1921,7 @@ public void testAutoGrowBeyondCustomLimit() { } @Test - public void testNestedGrowingList() { + void testNestedGrowingList() { Form form = new Form(); DataBinder binder = new DataBinder(form, "form"); MutablePropertyValues mpv = new MutablePropertyValues(); @@ -1937,7 +1937,7 @@ public void testNestedGrowingList() { } @Test - public void testFieldErrorAccessVariations() { + void testFieldErrorAccessVariations() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); assertThat(binder.getBindingResult().getGlobalError()).isNull(); @@ -1958,7 +1958,7 @@ public void testFieldErrorAccessVariations() { } @Test // SPR-14888 - public void testSetAutoGrowCollectionLimit() { + void testSetAutoGrowCollectionLimit() { BeanWithIntegerList tb = new BeanWithIntegerList(); DataBinder binder = new DataBinder(tb); binder.setAutoGrowCollectionLimit(257); @@ -1968,11 +1968,11 @@ public void testSetAutoGrowCollectionLimit() { binder.bind(pvs); assertThat(tb.getIntegerList().size()).isEqualTo(257); assertThat(tb.getIntegerList().get(256)).isEqualTo(Integer.valueOf(1)); - assertThat(binder.getBindingResult().getFieldValue("integerList[256]")).isEqualTo(Integer.valueOf(1)); + assertThat(binder.getBindingResult().getFieldValue("integerList[256]")).isEqualTo(1); } @Test // SPR-14888 - public void testSetAutoGrowCollectionLimitAfterInitialization() { + void testSetAutoGrowCollectionLimitAfterInitialization() { DataBinder binder = new DataBinder(new BeanWithIntegerList()); binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); assertThatIllegalStateException().isThrownBy(() -> @@ -1981,7 +1981,7 @@ public void testSetAutoGrowCollectionLimitAfterInitialization() { } @Test // SPR-15009 - public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() { + void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForBeanPropertyAccess() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); DefaultMessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver(); @@ -1998,7 +1998,7 @@ public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForBea } @Test // SPR-15009 - public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() { + void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForDirectFieldAccess() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); DefaultMessageCodesResolver messageCodesResolver = new DefaultMessageCodesResolver(); @@ -2013,7 +2013,7 @@ public void testSetCustomMessageCodesResolverBeforeInitializeBindingResultForDir } @Test // SPR-15009 - public void testSetCustomMessageCodesResolverAfterInitializeBindingResult() { + void testSetCustomMessageCodesResolverAfterInitializeBindingResult() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.initBeanPropertyAccess(); @@ -2028,7 +2028,7 @@ public void testSetCustomMessageCodesResolverAfterInitializeBindingResult() { } @Test // SPR-15009 - public void testSetMessageCodesResolverIsNullAfterInitializeBindingResult() { + void testSetMessageCodesResolverIsNullAfterInitializeBindingResult() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.initBeanPropertyAccess(); @@ -2042,7 +2042,7 @@ public void testSetMessageCodesResolverIsNullAfterInitializeBindingResult() { } @Test // SPR-15009 - public void testCallSetMessageCodesResolverTwice() { + void testCallSetMessageCodesResolverTwice() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); @@ -2053,7 +2053,7 @@ public void testCallSetMessageCodesResolverTwice() { } @Test // gh-24347 - public void overrideBindingResultType() { + void overrideBindingResultType() { TestBean testBean = new TestBean(); DataBinder binder = new DataBinder(testBean, "testBean"); binder.initDirectFieldAccess(); diff --git a/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java index aa6cf358117f..68a1cc018da1 100644 --- a/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ObjectUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -109,7 +109,7 @@ void isEmptyCollection() { Set set = new HashSet<>(); set.add("foo"); assertThat(isEmpty(set)).isFalse(); - assertThat(isEmpty(Arrays.asList("foo"))).isFalse(); + assertThat(isEmpty(Collections.singletonList("foo"))).isFalse(); } @Test @@ -159,7 +159,7 @@ void toObjectArrayWithNull() { void toObjectArrayWithEmptyPrimitiveArray() { Object[] objects = ObjectUtils.toObjectArray(new byte[] {}); assertThat(objects).isNotNull(); - assertThat(objects.length).isEqualTo(0); + assertThat(objects).hasSize(0); } @Test @@ -179,7 +179,7 @@ void addObjectToArraySunnyDay() { String[] array = new String[] {"foo", "bar"}; String newElement = "baz"; Object[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertThat(newArray.length).isEqualTo(3); + assertThat(newArray).hasSize(3); assertThat(newArray[2]).isEqualTo(newElement); } @@ -188,7 +188,7 @@ void addObjectToArrayWhenEmpty() { String[] array = new String[0]; String newElement = "foo"; String[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertThat(newArray.length).isEqualTo(1); + assertThat(newArray).hasSize(1); assertThat(newArray[0]).isEqualTo(newElement); } @@ -198,7 +198,7 @@ void addObjectToSingleNonNullElementArray() { String[] array = new String[] {existingElement}; String newElement = "bar"; String[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertThat(newArray.length).isEqualTo(2); + assertThat(newArray).hasSize(2); assertThat(newArray[0]).isEqualTo(existingElement); assertThat(newArray[1]).isEqualTo(newElement); } @@ -208,8 +208,8 @@ void addObjectToSingleNullElementArray() { String[] array = new String[] {null}; String newElement = "bar"; String[] newArray = ObjectUtils.addObjectToArray(array, newElement); - assertThat(newArray.length).isEqualTo(2); - assertThat(newArray[0]).isEqualTo(null); + assertThat(newArray).hasSize(2); + assertThat(newArray[0]).isNull(); assertThat(newArray[1]).isEqualTo(newElement); } @@ -217,15 +217,15 @@ void addObjectToSingleNullElementArray() { void addObjectToNullArray() throws Exception { String newElement = "foo"; String[] newArray = ObjectUtils.addObjectToArray(null, newElement); - assertThat(newArray.length).isEqualTo(1); + assertThat(newArray).hasSize(1); assertThat(newArray[0]).isEqualTo(newElement); } @Test void addNullObjectToNullArray() throws Exception { Object[] newArray = ObjectUtils.addObjectToArray(null, null); - assertThat(newArray.length).isEqualTo(1); - assertThat(newArray[0]).isEqualTo(null); + assertThat(newArray).hasSize(1); + assertThat(newArray[0]).isNull(); } @Test @@ -260,7 +260,7 @@ void hashCodeWithDouble() { @Deprecated void hashCodeWithFloat() { float flt = 34.8f; - int expected = (new Float(flt)).hashCode(); + int expected = (Float.valueOf(flt)).hashCode(); assertThat(ObjectUtils.hashCode(flt)).isEqualTo(expected); } @@ -268,7 +268,7 @@ void hashCodeWithFloat() { @Deprecated void hashCodeWithLong() { long lng = 883L; - int expected = (new Long(lng)).hashCode(); + int expected = (Long.valueOf(lng)).hashCode(); assertThat(ObjectUtils.hashCode(lng)).isEqualTo(expected); } @@ -282,7 +282,7 @@ void identityToString() { @Test void identityToStringWithNullObject() { - assertThat(ObjectUtils.identityToString(null)).isEqualTo(""); + assertThat(ObjectUtils.identityToString(null)).isEmpty(); } @Test diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java index 922ec4a51a02..69bfa4fb4f4c 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -41,11 +41,11 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("rawtypes") -public class IndexingTests { +class IndexingTests { @Test @SuppressWarnings("unchecked") - public void indexIntoGenericPropertyContainingMap() { + void indexIntoGenericPropertyContainingMap() { Map property = new HashMap<>(); property.put("foo", "bar"); this.property = property; @@ -63,7 +63,7 @@ public void indexIntoGenericPropertyContainingMap() { @Test @SuppressWarnings("unchecked") - public void indexIntoGenericPropertyContainingMapObject() { + void indexIntoGenericPropertyContainingMapObject() { Map> property = new HashMap<>(); Map map = new HashMap<>(); map.put("foo", "bar"); @@ -112,7 +112,7 @@ public Class[] getSpecificTargetClasses() { } @Test - public void setGenericPropertyContainingMap() { + void setGenericPropertyContainingMap() { Map property = new HashMap<>(); property.put("foo", "bar"); this.property = property; @@ -127,7 +127,7 @@ public void setGenericPropertyContainingMap() { } @Test - public void setPropertyContainingMap() { + void setPropertyContainingMap() { Map property = new HashMap<>(); property.put(9, 3); this.parameterizedMap = property; @@ -144,7 +144,7 @@ public void setPropertyContainingMap() { public Map parameterizedMap; @Test - public void setPropertyContainingMapAutoGrow() { + void setPropertyContainingMapAutoGrow() { SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, false)); Expression expression = parser.parseExpression("parameterizedMap"); assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("java.util.Map"); @@ -156,7 +156,7 @@ public void setPropertyContainingMapAutoGrow() { } @Test - public void indexIntoGenericPropertyContainingList() { + void indexIntoGenericPropertyContainingList() { List property = new ArrayList<>(); property.add("bar"); this.property = property; @@ -169,7 +169,7 @@ public void indexIntoGenericPropertyContainingList() { } @Test - public void setGenericPropertyContainingList() { + void setGenericPropertyContainingList() { List property = new ArrayList<>(); property.add(3); this.property = property; @@ -184,7 +184,7 @@ public void setGenericPropertyContainingList() { } @Test - public void setGenericPropertyContainingListAutogrow() { + void setGenericPropertyContainingListAutogrow() { List property = new ArrayList<>(); this.property = property; SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); @@ -203,7 +203,7 @@ public void setGenericPropertyContainingListAutogrow() { public List decimals; @Test - public void autoGrowListOfElementsWithoutDefaultConstructor() { + void autoGrowListOfElementsWithoutDefaultConstructor() { this.decimals = new ArrayList<>(); SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); parser.parseExpression("decimals[0]").setValue(this, "123.4"); @@ -211,7 +211,7 @@ public void autoGrowListOfElementsWithoutDefaultConstructor() { } @Test - public void indexIntoPropertyContainingListContainingNullElement() { + void indexIntoPropertyContainingListContainingNullElement() { this.decimals = new ArrayList<>(); this.decimals.add(null); this.decimals.add(BigDecimal.ONE); @@ -221,7 +221,7 @@ public void indexIntoPropertyContainingListContainingNullElement() { } @Test - public void indexIntoPropertyContainingList() { + void indexIntoPropertyContainingList() { List property = new ArrayList<>(); property.add(3); this.parameterizedList = property; @@ -236,7 +236,7 @@ public void indexIntoPropertyContainingList() { public List parameterizedList; @Test - public void indexIntoPropertyContainingListOfList() { + void indexIntoPropertyContainingListOfList() { List> property = new ArrayList<>(); property.add(Arrays.asList(3)); this.parameterizedListOfList = property; @@ -251,7 +251,7 @@ public void indexIntoPropertyContainingListOfList() { public List> parameterizedListOfList; @Test - public void setPropertyContainingList() { + void setPropertyContainingList() { List property = new ArrayList<>(); property.add(3); this.parameterizedList = property; @@ -266,7 +266,7 @@ public void setPropertyContainingList() { } @Test - public void indexIntoGenericPropertyContainingNullList() { + void indexIntoGenericPropertyContainingNullList() { SpelParserConfiguration configuration = new SpelParserConfiguration(true, true); SpelExpressionParser parser = new SpelExpressionParser(configuration); Expression expression = parser.parseExpression("property"); @@ -282,7 +282,7 @@ public void indexIntoGenericPropertyContainingNullList() { } @Test - public void indexIntoGenericPropertyContainingGrowingList() { + void indexIntoGenericPropertyContainingGrowingList() { List property = new ArrayList<>(); this.property = property; SpelParserConfiguration configuration = new SpelParserConfiguration(true, true); @@ -300,7 +300,7 @@ public void indexIntoGenericPropertyContainingGrowingList() { } @Test - public void indexIntoGenericPropertyContainingGrowingList2() { + void indexIntoGenericPropertyContainingGrowingList2() { List property2 = new ArrayList<>(); this.property2 = property2; SpelParserConfiguration configuration = new SpelParserConfiguration(true, true); @@ -320,7 +320,7 @@ public void indexIntoGenericPropertyContainingGrowingList2() { public List property2; @Test - public void indexIntoGenericPropertyContainingArray() { + void indexIntoGenericPropertyContainingArray() { String[] property = new String[] { "bar" }; this.property = property; SpelExpressionParser parser = new SpelExpressionParser(); @@ -332,7 +332,7 @@ public void indexIntoGenericPropertyContainingArray() { } @Test - public void emptyList() { + void emptyList() { listOfScalarNotGeneric = new ArrayList(); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listOfScalarNotGeneric"); @@ -342,7 +342,7 @@ public void emptyList() { @SuppressWarnings("unchecked") @Test - public void resolveCollectionElementType() { + void resolveCollectionElementType() { listNotGeneric = new ArrayList(2); listNotGeneric.add(5); listNotGeneric.add(6); @@ -353,7 +353,7 @@ public void resolveCollectionElementType() { } @Test - public void resolveCollectionElementTypeNull() { + void resolveCollectionElementTypeNull() { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listNotGeneric"); assertThat(expression.getValueTypeDescriptor(this).toString()).isEqualTo("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.List"); @@ -370,7 +370,7 @@ public void resolveCollectionElementTypeNull() { @SuppressWarnings("unchecked") @Test - public void resolveMapKeyValueTypes() { + void resolveMapKeyValueTypes() { mapNotGeneric = new HashMap(); mapNotGeneric.put("baseAmount", 3.11); mapNotGeneric.put("bonusAmount", 7.17); @@ -384,12 +384,12 @@ public void resolveMapKeyValueTypes() { @SuppressWarnings("unchecked") @Test - public void testListOfScalar() { + void testListOfScalar() { listOfScalarNotGeneric = new ArrayList(1); listOfScalarNotGeneric.add("5"); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("listOfScalarNotGeneric[0]"); - assertThat(expression.getValue(this, Integer.class)).isEqualTo(new Integer(5)); + assertThat(expression.getValue(this, Integer.class)).isEqualTo(Integer.valueOf(5)); } public List listOfScalarNotGeneric; @@ -397,7 +397,7 @@ public void testListOfScalar() { @SuppressWarnings("unchecked") @Test - public void testListsOfMap() { + void testListsOfMap() { listOfMapsNotGeneric = new ArrayList(); Map map = new HashMap(); map.put("fruit", "apple"); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java index 92fef3bec695..baef9bd558c9 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -33,10 +33,10 @@ * @author Juergen Hoeller * @author Giovanni Dall'Oglio Risso */ -public class OperatorTests extends AbstractExpressionTests { +class OperatorTests extends AbstractExpressionTests { @Test - public void testEqual() { + void testEqual() { evaluate("3 == 5", false, Boolean.class); evaluate("5 == 3", false, Boolean.class); evaluate("6 == 6", true, Boolean.class); @@ -85,7 +85,7 @@ public void testEqual() { } @Test - public void testNotEqual() { + void testNotEqual() { evaluate("3 != 5", true, Boolean.class); evaluate("5 != 3", true, Boolean.class); evaluate("6 != 6", false, Boolean.class); @@ -134,7 +134,7 @@ public void testNotEqual() { } @Test - public void testLessThan() { + void testLessThan() { evaluate("5 < 5", false, Boolean.class); evaluate("3 < 5", true, Boolean.class); evaluate("5 < 3", false, Boolean.class); @@ -176,7 +176,7 @@ public void testLessThan() { } @Test - public void testLessThanOrEqual() { + void testLessThanOrEqual() { evaluate("3 <= 5", true, Boolean.class); evaluate("5 <= 3", false, Boolean.class); evaluate("6 <= 6", true, Boolean.class); @@ -225,7 +225,7 @@ public void testLessThanOrEqual() { } @Test - public void testGreaterThan() { + void testGreaterThan() { evaluate("3 > 5", false, Boolean.class); evaluate("5 > 3", true, Boolean.class); evaluate("3L > 5L", false, Boolean.class); @@ -266,7 +266,7 @@ public void testGreaterThan() { } @Test - public void testGreaterThanOrEqual() { + void testGreaterThanOrEqual() { evaluate("3 >= 5", false, Boolean.class); evaluate("5 >= 3", true, Boolean.class); evaluate("6 >= 6", true, Boolean.class); @@ -315,27 +315,27 @@ public void testGreaterThanOrEqual() { } @Test - public void testIntegerLiteral() { + void testIntegerLiteral() { evaluate("3", 3, Integer.class); } @Test - public void testRealLiteral() { + void testRealLiteral() { evaluate("3.5", 3.5d, Double.class); } @Test - public void testMultiplyStringInt() { + void testMultiplyStringInt() { evaluate("'a' * 5", "aaaaa", String.class); } @Test - public void testMultiplyDoubleDoubleGivesDouble() { + void testMultiplyDoubleDoubleGivesDouble() { evaluate("3.0d * 5.0d", 15.0d, Double.class); } @Test - public void testMixedOperandsBigDecimal() { + void testMixedOperandsBigDecimal() { evaluate("3 * new java.math.BigDecimal('5')", new BigDecimal("15"), BigDecimal.class); evaluate("3L * new java.math.BigDecimal('5')", new BigDecimal("15"), BigDecimal.class); evaluate("3.0d * new java.math.BigDecimal('5')", new BigDecimal("15.0"), BigDecimal.class); @@ -361,19 +361,19 @@ public void testMixedOperandsBigDecimal() { } @Test - public void testMathOperatorAdd02() { + void testMathOperatorAdd02() { evaluate("'hello' + ' ' + 'world'", "hello world", String.class); } @Test - public void testMathOperatorsInChains() { + void testMathOperatorsInChains() { evaluate("1+2+3",6,Integer.class); evaluate("2*3*4",24,Integer.class); evaluate("12-1-2",9,Integer.class); } @Test - public void testIntegerArithmetic() { + void testIntegerArithmetic() { evaluate("2 + 4", "6", Integer.class); evaluate("5 - 4", "1", Integer.class); evaluate("3 * 5", 15, Integer.class); @@ -388,7 +388,7 @@ public void testIntegerArithmetic() { } @Test - public void testPlus() throws Exception { + void testPlus() { evaluate("7 + 2", "9", Integer.class); evaluate("3.0f + 5.0f", 8.0f, Float.class); evaluate("3.0d + 5.0d", 8.0d, Double.class); @@ -419,7 +419,7 @@ public void testPlus() throws Exception { } @Test - public void testMinus() throws Exception { + void testMinus() { evaluate("'c' - 2", "a", String.class); evaluate("3.0f - 5.0f", -2.0f, Float.class); evaluateAndCheckError("'ab' - 2", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); @@ -437,7 +437,7 @@ public void testMinus() throws Exception { } @Test - public void testModulus() { + void testModulus() { evaluate("3%2",1,Integer.class); evaluate("3L%2L",1L,Long.class); evaluate("3.0f%2.0f",1f,Float.class); @@ -448,7 +448,7 @@ public void testModulus() { } @Test - public void testDivide() { + void testDivide() { evaluate("3.0f / 5.0f", 0.6f, Float.class); evaluate("4L/2L",2L,Long.class); evaluate("3.0f div 5.0f", 0.6f, Float.class); @@ -461,17 +461,17 @@ public void testDivide() { } @Test - public void testMathOperatorDivide_ConvertToDouble() { - evaluateAndAskForReturnType("8/4", new Double(2.0), Double.class); + void testMathOperatorDivide_ConvertToDouble() { + evaluateAndAskForReturnType("8/4", 2.0, Double.class); } @Test - public void testMathOperatorDivide04_ConvertToFloat() { - evaluateAndAskForReturnType("8/4", new Float(2.0), Float.class); + void testMathOperatorDivide04_ConvertToFloat() { + evaluateAndAskForReturnType("8/4", 2.0F, Float.class); } @Test - public void testDoubles() { + void testDoubles() { evaluate("3.0d == 5.0d", false, Boolean.class); evaluate("3.0d == 3.0d", true, Boolean.class); evaluate("3.0d != 5.0d", true, Boolean.class); @@ -484,7 +484,7 @@ public void testDoubles() { } @Test - public void testBigDecimals() { + void testBigDecimals() { evaluate("3 + new java.math.BigDecimal('5')", new BigDecimal("8"), BigDecimal.class); evaluate("3 - new java.math.BigDecimal('5')", new BigDecimal("-2"), BigDecimal.class); evaluate("3 * new java.math.BigDecimal('5')", new BigDecimal("15"), BigDecimal.class); @@ -495,7 +495,7 @@ public void testBigDecimals() { } @Test - public void testOperatorNames() throws Exception { + void testOperatorNames() { Operator node = getOperatorNode((SpelExpression)parser.parseExpression("1==3")); assertThat(node.getOperatorName()).isEqualTo("=="); @@ -534,13 +534,13 @@ public void testOperatorNames() throws Exception { } @Test - public void testOperatorOverloading() { + void testOperatorOverloading() { evaluateAndCheckError("'a' * '2'", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); evaluateAndCheckError("'a' ^ '2'", SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES); } @Test - public void testPower() { + void testPower() { evaluate("3^2",9,Integer.class); evaluate("3.0d^2.0d",9.0d,Double.class); evaluate("3L^2L",9L,Long.class); @@ -549,7 +549,7 @@ public void testPower() { } @Test - public void testMixedOperands_FloatsAndDoubles() { + void testMixedOperands_FloatsAndDoubles() { evaluate("3.0d + 5.0f", 8.0d, Double.class); evaluate("3.0D - 5.0f", -2.0d, Double.class); evaluate("3.0f * 5.0d", 15.0d, Double.class); @@ -558,7 +558,7 @@ public void testMixedOperands_FloatsAndDoubles() { } @Test - public void testMixedOperands_DoublesAndInts() { + void testMixedOperands_DoublesAndInts() { evaluate("3.0d + 5", 8.0d, Double.class); evaluate("3.0D - 5", -2.0d, Double.class); evaluate("3.0f * 5", 15.0f, Float.class); @@ -569,7 +569,7 @@ public void testMixedOperands_DoublesAndInts() { } @Test - public void testStrings() { + void testStrings() { evaluate("'abc' == 'abc'", true, Boolean.class); evaluate("'abc' == 'def'", false, Boolean.class); evaluate("'abc' != 'abc'", false, Boolean.class); @@ -577,7 +577,7 @@ public void testStrings() { } @Test - public void testLongs() { + void testLongs() { evaluate("3L == 4L", false, Boolean.class); evaluate("3L == 3L", true, Boolean.class); evaluate("3L != 4L", true, Boolean.class); @@ -588,7 +588,7 @@ public void testLongs() { } @Test - public void testBigIntegers() { + void testBigIntegers() { evaluate("3 + new java.math.BigInteger('5')", new BigInteger("8"), BigInteger.class); evaluate("3 - new java.math.BigInteger('5')", new BigInteger("-2"), BigInteger.class); evaluate("3 * new java.math.BigInteger('5')", new BigInteger("15"), BigInteger.class); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java index 74af20b3f1ed..49fa8c182c44 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java @@ -128,7 +128,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests { @Test - public void typeReference() throws Exception { + void typeReference() { expression = parse("T(String)"); assertThat(expression.getValue()).isEqualTo(String.class); assertCanCompile(expression); @@ -196,7 +196,7 @@ public void typeReference() throws Exception { @SuppressWarnings("unchecked") @Test - public void operatorInstanceOf() throws Exception { + void operatorInstanceOf() { expression = parse("'xyz' instanceof T(String)"); assertThat(expression.getValue()).isEqualTo(true); assertCanCompile(expression); @@ -245,7 +245,7 @@ public void operatorInstanceOf() throws Exception { } @Test - public void operatorInstanceOf_SPR14250() throws Exception { + void operatorInstanceOf_SPR14250() throws Exception { // primitive left operand - should get boxed, return true expression = parse("3 instanceof T(Integer)"); assertThat(expression.getValue()).isEqualTo(true); @@ -292,7 +292,7 @@ public void operatorInstanceOf_SPR14250() throws Exception { } @Test - public void stringLiteral() throws Exception { + void stringLiteral() throws Exception { expression = parser.parseExpression("'abcde'"); assertThat(expression.getValue(new TestClass1(), String.class)).isEqualTo("abcde"); assertCanCompile(expression); @@ -307,18 +307,18 @@ public void stringLiteral() throws Exception { } @Test - public void nullLiteral() throws Exception { + void nullLiteral() throws Exception { expression = parser.parseExpression("null"); Object resultI = expression.getValue(new TestClass1(), Object.class); assertCanCompile(expression); Object resultC = expression.getValue(new TestClass1(), Object.class); - assertThat(resultI).isEqualTo(null); - assertThat(resultC).isEqualTo(null); - assertThat(resultC).isEqualTo(null); + assertThat(resultI).isNull(); + assertThat(resultC).isNull(); + assertThat(resultC).isNull(); } @Test - public void realLiteral() throws Exception { + void realLiteral() throws Exception { expression = parser.parseExpression("3.4d"); double resultI = expression.getValue(new TestClass1(), Double.TYPE); assertCanCompile(expression); @@ -332,7 +332,7 @@ public void realLiteral() throws Exception { @SuppressWarnings("rawtypes") @Test - public void inlineList() throws Exception { + void inlineList() throws Exception { expression = parser.parseExpression("'abcde'.substring({1,3,4}[0])"); Object o = expression.getValue(); assertThat(o).isEqualTo("bcde"); @@ -371,7 +371,7 @@ public void inlineList() throws Exception { @SuppressWarnings("rawtypes") @Test - public void nestedInlineLists() throws Exception { + void nestedInlineLists() throws Exception { Object o = null; expression = parser.parseExpression("{{1,2,3},{4,5,6},{7,8,9}}"); @@ -446,7 +446,7 @@ public void nestedInlineLists() throws Exception { } @Test - public void intLiteral() throws Exception { + void intLiteral() throws Exception { expression = parser.parseExpression("42"); int resultI = expression.getValue(new TestClass1(), Integer.TYPE); assertCanCompile(expression); @@ -477,7 +477,7 @@ public void intLiteral() throws Exception { } @Test - public void longLiteral() throws Exception { + void longLiteral() throws Exception { expression = parser.parseExpression("99L"); long resultI = expression.getValue(new TestClass1(), Long.TYPE); assertCanCompile(expression); @@ -487,24 +487,24 @@ public void longLiteral() throws Exception { } @Test - public void booleanLiteral() throws Exception { + void booleanLiteral() throws Exception { expression = parser.parseExpression("true"); boolean resultI = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(true); + assertThat(resultI).isTrue(); assertThat(SpelCompiler.compile(expression)).isTrue(); boolean resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultC).isEqualTo(true); + assertThat(resultC).isTrue(); expression = parser.parseExpression("false"); resultI = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(false); + assertThat(resultI).isFalse(); assertThat(SpelCompiler.compile(expression)).isTrue(); resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultC).isEqualTo(false); + assertThat(resultC).isFalse(); } @Test - public void floatLiteral() throws Exception { + void floatLiteral() throws Exception { expression = parser.parseExpression("3.4f"); float resultI = expression.getValue(new TestClass1(), Float.TYPE); assertCanCompile(expression); @@ -517,42 +517,42 @@ public void floatLiteral() throws Exception { } @Test - public void opOr() throws Exception { + void opOr() throws Exception { Expression expression = parser.parseExpression("false or false"); boolean resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); boolean resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(false); - assertThat(resultC).isEqualTo(false); + assertThat(resultI).isFalse(); + assertThat(resultC).isFalse(); expression = parser.parseExpression("false or true"); resultI = expression.getValue(1, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(true); - assertThat(resultC).isEqualTo(true); + assertThat(resultI).isTrue(); + assertThat(resultC).isTrue(); expression = parser.parseExpression("true or false"); resultI = expression.getValue(1, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(true); - assertThat(resultC).isEqualTo(true); + assertThat(resultI).isTrue(); + assertThat(resultC).isTrue(); expression = parser.parseExpression("true or true"); resultI = expression.getValue(1, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(true); - assertThat(resultC).isEqualTo(true); + assertThat(resultI).isTrue(); + assertThat(resultC).isTrue(); TestClass4 tc = new TestClass4(); expression = parser.parseExpression("getfalse() or gettrue()"); resultI = expression.getValue(tc, Boolean.TYPE); assertCanCompile(expression); resultC = expression.getValue(tc, Boolean.TYPE); - assertThat(resultI).isEqualTo(true); - assertThat(resultC).isEqualTo(true); + assertThat(resultI).isTrue(); + assertThat(resultC).isTrue(); // Can't compile this as we aren't going down the getfalse() branch in our evaluation expression = parser.parseExpression("gettrue() or getfalse()"); @@ -584,29 +584,29 @@ public void opAnd() throws Exception { boolean resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); boolean resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(false); - assertThat(resultC).isEqualTo(false); + assertThat(resultI).isFalse(); + assertThat(resultC).isFalse(); expression = parser.parseExpression("false and true"); resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(false); - assertThat(resultC).isEqualTo(false); + assertThat(resultI).isFalse(); + assertThat(resultC).isFalse(); expression = parser.parseExpression("true and false"); resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(false); - assertThat(resultC).isEqualTo(false); + assertThat(resultI).isFalse(); + assertThat(resultC).isFalse(); expression = parser.parseExpression("true and true"); resultI = expression.getValue(1, Boolean.TYPE); SpelCompiler.compile(expression); resultC = expression.getValue(1, Boolean.TYPE); - assertThat(resultI).isEqualTo(true); - assertThat(resultC).isEqualTo(true); + assertThat(resultI).isTrue(); + assertThat(resultC).isTrue(); TestClass4 tc = new TestClass4(); @@ -3481,7 +3481,7 @@ public void constructorReference() throws Exception { assertThat(tc8.s).isEqualTo("123"); assertThat(tc8.d).isCloseTo(4.0d, within(0.5d)); - assertThat(tc8.z).isEqualTo(true); + assertThat(tc8.z).isTrue(); // no-arg ctor expression = parser.parseExpression("new " + testclass8 + "()"); @@ -3507,7 +3507,7 @@ public void constructorReference() throws Exception { } @Test - public void methodReferenceReflectiveMethodSelectionWithVarargs() throws Exception { + void methodReferenceReflectiveMethodSelectionWithVarargs() throws Exception { TestClass10 tc = new TestClass10(); // Should call the non varargs version of concat @@ -3526,11 +3526,11 @@ public void methodReferenceReflectiveMethodSelectionWithVarargs() throws Excepti expression = parser.parseExpression("concat()"); assertCantCompile(expression); expression.getValue(tc); - assertThat(tc.s).isEqualTo(""); + assertThat(tc.s).isEmpty(); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertThat(tc.s).isEqualTo(""); + assertThat(tc.s).isEmpty(); tc.reset(); // Should call the non varargs version of concat @@ -3549,27 +3549,27 @@ public void methodReferenceReflectiveMethodSelectionWithVarargs() throws Excepti expression = parser.parseExpression("concat2()"); assertCantCompile(expression); expression.getValue(tc); - assertThat(tc.s).isEqualTo(""); + assertThat(tc.s).isEmpty(); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertThat(tc.s).isEqualTo(""); + assertThat(tc.s).isEmpty(); tc.reset(); } @Test - public void methodReferenceVarargs() throws Exception { + void methodReferenceVarargs() { TestClass5 tc = new TestClass5(); // varargs string expression = parser.parseExpression("eleven()"); assertCantCompile(expression); expression.getValue(tc); - assertThat(tc.s).isEqualTo(""); + assertThat(tc.s).isEmpty(); assertCanCompile(expression); tc.reset(); expression.getValue(tc); - assertThat(tc.s).isEqualTo(""); + assertThat(tc.s).isEmpty(); tc.reset(); // varargs string @@ -3840,7 +3840,7 @@ public void methodReferenceVarargs() throws Exception { } @Test - public void methodReference() throws Exception { + void methodReference() { TestClass5 tc = new TestClass5(); // non-static method, no args, void return @@ -3985,7 +3985,7 @@ public void methodReference() throws Exception { } @Test - public void errorHandling() throws Exception { + void errorHandling() { TestClass5 tc = new TestClass5(); // changing target @@ -4040,7 +4040,7 @@ public void errorHandling() throws Exception { } @Test - public void methodReference_staticMethod() throws Exception { + void methodReference_staticMethod() { Expression expression = parser.parseExpression("T(Integer).valueOf(42)"); int resultI = expression.getValue(new TestClass1(), Integer.TYPE); assertCanCompile(expression); @@ -4050,7 +4050,7 @@ public void methodReference_staticMethod() throws Exception { } @Test - public void methodReference_literalArguments_int() throws Exception { + void methodReference_literalArguments_int() { Expression expression = parser.parseExpression("'abcd'.substring(1,3)"); String resultI = expression.getValue(new TestClass1(), String.class); assertCanCompile(expression); @@ -4060,7 +4060,7 @@ public void methodReference_literalArguments_int() throws Exception { } @Test - public void methodReference_simpleInstanceMethodNoArg() throws Exception { + void methodReference_simpleInstanceMethodNoArg() { Expression expression = parser.parseExpression("toString()"); String resultI = expression.getValue(42, String.class); assertCanCompile(expression); @@ -4070,7 +4070,7 @@ public void methodReference_simpleInstanceMethodNoArg() throws Exception { } @Test - public void methodReference_simpleInstanceMethodNoArgReturnPrimitive() throws Exception { + void methodReference_simpleInstanceMethodNoArgReturnPrimitive() { expression = parser.parseExpression("intValue()"); int resultI = expression.getValue(42, Integer.TYPE); assertThat(resultI).isEqualTo(42); @@ -4080,7 +4080,7 @@ public void methodReference_simpleInstanceMethodNoArgReturnPrimitive() throws Ex } @Test - public void methodReference_simpleInstanceMethodOneArgReturnPrimitive1() throws Exception { + void methodReference_simpleInstanceMethodOneArgReturnPrimitive1() { Expression expression = parser.parseExpression("indexOf('b')"); int resultI = expression.getValue("abc", Integer.TYPE); assertCanCompile(expression); @@ -4090,7 +4090,7 @@ public void methodReference_simpleInstanceMethodOneArgReturnPrimitive1() throws } @Test - public void methodReference_simpleInstanceMethodOneArgReturnPrimitive2() throws Exception { + void methodReference_simpleInstanceMethodOneArgReturnPrimitive2() { expression = parser.parseExpression("charAt(2)"); char resultI = expression.getValue("abc", Character.TYPE); assertThat(resultI).isEqualTo('c'); @@ -4100,7 +4100,7 @@ public void methodReference_simpleInstanceMethodOneArgReturnPrimitive2() throws } @Test - public void compoundExpression() throws Exception { + void compoundExpression() { Payload payload = new Payload(); expression = parser.parseExpression("DR[0]"); assertThat(expression.getValue(payload).toString()).isEqualTo("instanceof Two"); @@ -4137,7 +4137,7 @@ public void compoundExpression() throws Exception { } @Test - public void mixingItUp_indexerOpEqTernary() throws Exception { + void mixingItUp_indexerOpEqTernary() { Map m = new HashMap<>(); m.put("andy","778"); @@ -4150,7 +4150,7 @@ public void mixingItUp_indexerOpEqTernary() throws Exception { } @Test - public void propertyReference() throws Exception { + void propertyReference() { TestClass6 tc = new TestClass6(); // non static field @@ -4190,7 +4190,7 @@ public void propertyReference() throws Exception { } @Test - public void propertyReferenceVisibility_SPR12771() { + void propertyReferenceVisibility_SPR12771() { StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("httpServletRequest", HttpServlet3RequestFactory.getOne()); // Without a fix compilation was inserting a checkcast to a private type @@ -4202,7 +4202,7 @@ public void propertyReferenceVisibility_SPR12771() { @SuppressWarnings("unchecked") @Test - public void indexer() throws Exception { + void indexer() { String[] sss = new String[] {"a","b","c"}; Number[] ns = new Number[] {2,8,9}; int[] is = new int[] {8,9,10}; @@ -4509,7 +4509,7 @@ public void indexer() throws Exception { } @Test - public void plusNeedingCheckcast_SPR12426() { + void plusNeedingCheckcast_SPR12426() { expression = parser.parseExpression("object + ' world'"); Object v = expression.getValue(new FooObject()); assertThat(v).isEqualTo("hello world"); @@ -4524,7 +4524,7 @@ public void plusNeedingCheckcast_SPR12426() { } @Test - public void mixingItUp_propertyAccessIndexerOpLtTernaryRootNull() throws Exception { + void mixingItUp_propertyAccessIndexerOpLtTernaryRootNull() { Payload payload = new Payload(); expression = parser.parseExpression("DR[0].three"); @@ -4552,7 +4552,7 @@ public void mixingItUp_propertyAccessIndexerOpLtTernaryRootNull() throws Excepti } @Test - public void variantGetter() throws Exception { + void variantGetter() throws Exception { Payload2Holder holder = new Payload2Holder(); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.addPropertyAccessor(new MyAccessor()); @@ -4566,7 +4566,7 @@ public void variantGetter() throws Exception { } @Test - public void compilerWithGenerics_12040() { + void compilerWithGenerics_12040() { expression = parser.parseExpression("payload!=2"); assertThat(expression.getValue(new GenericMessageTestHelper<>(4), Boolean.class)).isTrue(); assertCanCompile(expression); @@ -4675,7 +4675,7 @@ public void compilerWithGenerics_12040() { // The new helper class here uses an upper bound on the generic @Test - public void compilerWithGenerics_12040_2() { + void compilerWithGenerics_12040_2() { expression = parser.parseExpression("payload/2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4))).isEqualTo(2); assertCanCompile(expression); @@ -4719,7 +4719,7 @@ public void compilerWithGenerics_12040_2() { // The other numeric operators @Test - public void compilerWithGenerics_12040_3() { + void compilerWithGenerics_12040_3() { expression = parser.parseExpression("payload >= 2"); assertThat(expression.getValue(new GenericMessageTestHelper2<>(4), Boolean.TYPE)).isTrue(); assertCanCompile(expression); @@ -4762,7 +4762,7 @@ public void compilerWithGenerics_12040_3() { } @Test - public void indexerMapAccessor_12045() throws Exception { + void indexerMapAccessor_12045() throws Exception { SpelParserConfiguration spc = new SpelParserConfiguration( SpelCompilerMode.IMMEDIATE,getClass().getClassLoader()); SpelExpressionParser sep = new SpelExpressionParser(spc); @@ -4791,7 +4791,7 @@ public void indexerMapAccessor_12045() throws Exception { } @Test - public void elvisOperator_SPR15192() { + void elvisOperator_SPR15192() { SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null); Expression exp; @@ -4875,7 +4875,7 @@ public void elvisOperator_SPR15192() { } @Test - public void elvisOperator_SPR17214() throws Exception { + void elvisOperator_SPR17214() { SpelParserConfiguration spc = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null); SpelExpressionParser sep = new SpelExpressionParser(spc); @@ -4923,7 +4923,7 @@ public void elvisOperator_SPR17214() throws Exception { } @Test - public void testNullComparison_SPR22358() { + void testNullComparison_SPR22358() { SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.OFF, null); SpelExpressionParser parser = new SpelExpressionParser(configuration); StandardEvaluationContext ctx = new StandardEvaluationContext(); @@ -5004,7 +5004,7 @@ private void verifyCompilationAndBehaviourWithNull2(String expressionText, SpelE } @Test - public void ternaryOperator_SPR15192() { + void ternaryOperator_SPR15192() { SpelParserConfiguration configuration = new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null); Expression exp; StandardEvaluationContext context = new StandardEvaluationContext(); @@ -5048,9 +5048,9 @@ public void ternaryOperator_SPR15192() { // null condition exp = new SpelExpressionParser(configuration).parseExpression("3==3?null:4L"); - assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo(null); + assertThat(exp.getValue(context, new Foo(), String.class)).isNull(); assertCanCompile(exp); - assertThat(exp.getValue(context, new Foo(), String.class)).isEqualTo(null); + assertThat(exp.getValue(context, new Foo(), String.class)).isNull(); assertIsCompiled(exp); // variable access returning primitive @@ -5078,7 +5078,7 @@ public void ternaryOperator_SPR15192() { } @Test - public void repeatedCompilation() throws Exception { + void repeatedCompilation() throws Exception { // Verifying that after a number of compilations, the classloaders // used to load the compiled expressions are discarded/replaced. // See SpelCompiler.loadClass() @@ -6204,9 +6204,9 @@ public class Reg { public Reg(int v) { this._value = v; - this._valueL = new Long(v); - this._valueD = new Double(v); - this._valueF = new Float(v); + this._valueL = Long.valueOf(v); + this._valueD = (double) v; + this._valueF = (float) v; } public Integer getValue() { @@ -6243,16 +6243,16 @@ public Float getValueF2() { public void setValue(Integer value) { _value = value; - _valueL = value==null?null:new Long(value); - _valueD = value==null?null:new Double(value); - _valueF = value==null?null:new Float(value); + _valueL = value==null?null:Long.valueOf(value); + _valueD = value==null?null:Double.valueOf(value); + _valueF = value==null?null:Float.valueOf(value); } public void setValue2(Integer value) { _value2 = value; - _valueL2 = value==null?null:new Long(value); - _valueD2 = value==null?null:new Double(value); - _valueF2 = value==null?null:new Float(value); + _valueL2 = value==null?null:Long.valueOf(value); + _valueD2 = value==null?null:Double.valueOf(value); + _valueF2 = value==null?null:Float.valueOf(value); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index b114826270b5..09e73591350e 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -74,35 +74,35 @@ * @author Phillip Webb * @author Sam Brannen */ -public class SpelReproTests extends AbstractExpressionTests { +class SpelReproTests extends AbstractExpressionTests { @Test - public void NPE_SPR5661() { + void NPE_SPR5661() { evaluate("joinThreeStrings('a',null,'c')", "anullc", String.class); } @Test - public void SWF1086() { + void SWF1086() { evaluate("printDouble(T(java.math.BigDecimal).valueOf(14.35))", "14.35", String.class); } @Test - public void doubleCoercion() { + void doubleCoercion() { evaluate("printDouble(14.35)", "14.35", String.class); } @Test - public void doubleArrayCoercion() { + void doubleArrayCoercion() { evaluate("printDoubles(getDoublesAsStringList())", "{14.35, 15.45}", String.class); } @Test - public void SPR5899() { + void SPR5899() { StandardEvaluationContext context = new StandardEvaluationContext(new Spr5899Class()); Expression expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(12)"); assertThat(expr.getValue(context)).isEqualTo(12); expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(null)"); - assertThat(expr.getValue(context)).isEqualTo(null); + assertThat(expr.getValue(context)).isNull(); expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)"); assertThatExceptionOfType(EvaluationException.class).isThrownBy( expr::getValue); @@ -133,7 +133,7 @@ public void SPR5899() { } @Test - public void SPR5905_InnerTypeReferences() { + void SPR5905_InnerTypeReferences() { StandardEvaluationContext context = new StandardEvaluationContext(new Spr5899Class()); Expression expr = new SpelExpressionParser().parseRaw("T(java.util.Map$Entry)"); assertThat(expr.getValue(context)).isEqualTo(Map.Entry.class); @@ -146,7 +146,7 @@ public void SPR5905_InnerTypeReferences() { } @Test - public void SPR5804() { + void SPR5804() { Map m = new HashMap<>(); m.put("foo", "bar"); StandardEvaluationContext context = new StandardEvaluationContext(m); // root is a map instance @@ -156,7 +156,7 @@ public void SPR5804() { } @Test - public void SPR5847() { + void SPR5847() { StandardEvaluationContext context = new StandardEvaluationContext(new TestProperties()); String name = null; Expression expr = null; @@ -192,7 +192,7 @@ public void SPR5847() { } @Test - public void NPE_SPR5673() { + void NPE_SPR5673() { ParserContext hashes = TemplateExpressionParsingTests.HASH_DELIMITED_PARSER_CONTEXT; ParserContext dollars = TemplateExpressionParsingTests.DEFAULT_TEMPLATE_PARSER_CONTEXT; @@ -227,7 +227,7 @@ public void NPE_SPR5673() { } @Test - public void propertyAccessOnNullTarget_SPR5663() throws AccessException { + void propertyAccessOnNullTarget_SPR5663() throws AccessException { PropertyAccessor accessor = new ReflectivePropertyAccessor(); EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); assertThat(accessor.canRead(context, null, "abc")).isFalse(); @@ -239,7 +239,7 @@ public void propertyAccessOnNullTarget_SPR5663() throws AccessException { } @Test - public void nestedProperties_SPR6923() { + void nestedProperties_SPR6923() { StandardEvaluationContext context = new StandardEvaluationContext(new Foo()); Expression expr = new SpelExpressionParser().parseRaw("resource.resource.server"); String name = expr.getValue(context, String.class); @@ -248,7 +248,7 @@ public void nestedProperties_SPR6923() { /** Should be accessing Goo.getKey because 'bar' field evaluates to "key" */ @Test - public void indexingAsAPropertyAccess_SPR6968_1() { + void indexingAsAPropertyAccess_SPR6968_1() { StandardEvaluationContext context = new StandardEvaluationContext(new Goo()); String name = null; Expression expr = null; @@ -261,7 +261,7 @@ public void indexingAsAPropertyAccess_SPR6968_1() { /** Should be accessing Goo.getKey because 'bar' variable evaluates to "key" */ @Test - public void indexingAsAPropertyAccess_SPR6968_2() { + void indexingAsAPropertyAccess_SPR6968_2() { StandardEvaluationContext context = new StandardEvaluationContext(new Goo()); context.setVariable("bar", "key"); String name = null; @@ -275,7 +275,7 @@ public void indexingAsAPropertyAccess_SPR6968_2() { /** $ related identifiers */ @Test - public void dollarPrefixedIdentifier_SPR7100() { + void dollarPrefixedIdentifier_SPR7100() { Holder h = new Holder(); StandardEvaluationContext context = new StandardEvaluationContext(h); context.addPropertyAccessor(new MapAccessor()); @@ -315,7 +315,7 @@ public void dollarPrefixedIdentifier_SPR7100() { /** Should be accessing Goo.wibble field because 'bar' variable evaluates to "wibble" */ @Test - public void indexingAsAPropertyAccess_SPR6968_3() { + void indexingAsAPropertyAccess_SPR6968_3() { StandardEvaluationContext context = new StandardEvaluationContext(new Goo()); context.setVariable("bar", "wibble"); String name = null; @@ -333,7 +333,7 @@ public void indexingAsAPropertyAccess_SPR6968_3() { * "wibble" */ @Test - public void indexingAsAPropertyAccess_SPR6968_4() { + void indexingAsAPropertyAccess_SPR6968_4() { Goo g = Goo.instance; StandardEvaluationContext context = new StandardEvaluationContext(g); context.setVariable("bar", "wibble"); @@ -348,7 +348,7 @@ public void indexingAsAPropertyAccess_SPR6968_4() { /** Should be accessing Goo.setKey field because 'bar' variable evaluates to "key" */ @Test - public void indexingAsAPropertyAccess_SPR6968_5() { + void indexingAsAPropertyAccess_SPR6968_5() { Goo g = Goo.instance; StandardEvaluationContext context = new StandardEvaluationContext(g); Expression expr = null; @@ -360,7 +360,7 @@ public void indexingAsAPropertyAccess_SPR6968_5() { } @Test - public void dollars() { + void dollars() { StandardEvaluationContext context = new StandardEvaluationContext(new XX()); Expression expr = null; expr = new SpelExpressionParser().parseRaw("m['$foo']"); @@ -369,7 +369,7 @@ public void dollars() { } @Test - public void dollars2() { + void dollars2() { StandardEvaluationContext context = new StandardEvaluationContext(new XX()); Expression expr = null; expr = new SpelExpressionParser().parseRaw("m[$foo]"); @@ -421,7 +421,7 @@ public boolean isTemplate() { }; @Test - public void beanResolution() { + void beanResolution() { StandardEvaluationContext context = new StandardEvaluationContext(new XX()); Expression expr = null; @@ -443,12 +443,12 @@ public void beanResolution() { // bean does not exist expr = new SpelExpressionParser().parseRaw("@bar"); - assertThat(expr.getValue(context, String.class)).isEqualTo(null); + assertThat(expr.getValue(context, String.class)).isNull(); // bean name will cause AccessException expr = new SpelExpressionParser().parseRaw("@goo"); try { - assertThat(expr.getValue(context, String.class)).isEqualTo(null); + assertThat(expr.getValue(context, String.class)).isNull(); } catch (SpelEvaluationException see) { assertThat(see.getMessageCode()).isEqualTo(SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION); @@ -472,7 +472,7 @@ public void beanResolution() { } @Test - public void elvis_SPR7209_1() { + void elvis_SPR7209_1() { StandardEvaluationContext context = new StandardEvaluationContext(new XX()); Expression expr = null; @@ -482,14 +482,14 @@ public void elvis_SPR7209_1() { expr = new SpelExpressionParser().parseRaw("?:'default'"); assertThat(expr.getValue()).isEqualTo("default"); expr = new SpelExpressionParser().parseRaw("?:"); - assertThat(expr.getValue()).isEqualTo(null); + assertThat(expr.getValue()).isNull(); // Different parts of ternary expression are null assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> new SpelExpressionParser().parseRaw("(?'abc':'default')").getValue(context)) .satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_CONVERSION_ERROR)); expr = new SpelExpressionParser().parseRaw("(false?'abc':null)"); - assertThat(expr.getValue()).isEqualTo(null); + assertThat(expr.getValue()).isNull(); // Assignment assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> @@ -498,7 +498,7 @@ public void elvis_SPR7209_1() { } @Test - public void elvis_SPR7209_2() { + void elvis_SPR7209_2() { Expression expr = null; // Have empty string treated as null for elvis expr = new SpelExpressionParser().parseRaw("?:'default'"); @@ -510,7 +510,7 @@ public void elvis_SPR7209_2() { } @Test - public void mapOfMap_SPR7244() { + void mapOfMap_SPR7244() { Map map = new LinkedHashMap<>(); map.put("uri", "http:"); Map nameMap = new LinkedHashMap<>(); @@ -531,7 +531,7 @@ public void mapOfMap_SPR7244() { } @Test - public void projectionTypeDescriptors_1() { + void projectionTypeDescriptors_1() { StandardEvaluationContext context = new StandardEvaluationContext(new C()); SpelExpressionParser parser = new SpelExpressionParser(); String el1 = "ls.![#this.equals('abc')]"; @@ -540,11 +540,11 @@ public void projectionTypeDescriptors_1() { // value is list containing [true,false] assertThat(value.get(0).getClass()).isEqualTo(Boolean.class); TypeDescriptor evaluated = exp.getValueTypeDescriptor(context); - assertThat(evaluated.getElementTypeDescriptor()).isEqualTo(null); + assertThat(evaluated.getElementTypeDescriptor()).isNull(); } @Test - public void projectionTypeDescriptors_2() { + void projectionTypeDescriptors_2() { StandardEvaluationContext context = new StandardEvaluationContext(new C()); SpelExpressionParser parser = new SpelExpressionParser(); String el1 = "as.![#this.equals('abc')]"; @@ -557,7 +557,7 @@ public void projectionTypeDescriptors_2() { } @Test - public void projectionTypeDescriptors_3() { + void projectionTypeDescriptors_3() { StandardEvaluationContext context = new StandardEvaluationContext(new C()); SpelExpressionParser parser = new SpelExpressionParser(); String el1 = "ms.![key.equals('abc')]"; @@ -566,11 +566,11 @@ public void projectionTypeDescriptors_3() { // value is list containing [true,false] assertThat(value.get(0).getClass()).isEqualTo(Boolean.class); TypeDescriptor evaluated = exp.getValueTypeDescriptor(context); - assertThat(evaluated.getElementTypeDescriptor()).isEqualTo(null); + assertThat(evaluated.getElementTypeDescriptor()).isNull(); } @Test - public void greaterThanWithNulls_SPR7840() { + void greaterThanWithNulls_SPR7840() { List list = new ArrayList<>(); list.add(new D("aaa")); list.add(new D("bbb")); @@ -605,7 +605,7 @@ public void greaterThanWithNulls_SPR7840() { * than a unboxing conversion. */ @Test - public void conversionPriority_SPR8224() throws Exception { + void conversionPriority_SPR8224() throws Exception { @SuppressWarnings("unused") class ConversionPriority1 { @@ -637,7 +637,7 @@ public int getX(Number i) { ConversionPriority1 target = new ConversionPriority1(); MethodExecutor me = new ReflectiveMethodResolver(true).resolve(emptyEvalContext, target, "getX", args); // MethodInvoker chooses getX(int i) when passing Integer - final int actual = (Integer) me.execute(emptyEvalContext, target, new Integer(42)).getValue(); + final int actual = (Integer) me.execute(emptyEvalContext, target, Integer.valueOf(42)).getValue(); // Compiler chooses getX(Number i) when passing Integer final int compiler = target.getX(INTEGER); // Fails! @@ -646,7 +646,7 @@ public int getX(Number i) { ConversionPriority2 target2 = new ConversionPriority2(); MethodExecutor me2 = new ReflectiveMethodResolver(true).resolve(emptyEvalContext, target2, "getX", args); // MethodInvoker chooses getX(int i) when passing Integer - int actual2 = (Integer) me2.execute(emptyEvalContext, target2, new Integer(42)).getValue(); + int actual2 = (Integer) me2.execute(emptyEvalContext, target2, Integer.valueOf(42)).getValue(); // Compiler chooses getX(Number i) when passing Integer int compiler2 = target2.getX(INTEGER); // Fails! @@ -659,7 +659,7 @@ public int getX(Number i) { * method accepting 'long' is ok. */ @Test - public void wideningPrimitiveConversion_SPR8224() throws Exception { + void wideningPrimitiveConversion_SPR8224() throws Exception { class WideningPrimitiveConversion { public int getX(long i) { @@ -667,7 +667,7 @@ public int getX(long i) { } } - final Integer INTEGER_VALUE = Integer.valueOf(7); + final Integer INTEGER_VALUE = 7; WideningPrimitiveConversion target = new WideningPrimitiveConversion(); EvaluationContext emptyEvalContext = new StandardEvaluationContext(); @@ -682,7 +682,7 @@ public int getX(long i) { } @Test - public void varargsAgainstProxy_SPR16122() { + void varargsAgainstProxy_SPR16122() { SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("process('a', 'b')"); @@ -696,7 +696,7 @@ public void varargsAgainstProxy_SPR16122() { } @Test - public void testCompiledExpressionForProxy_SPR16191() { + void testCompiledExpressionForProxy_SPR16191() { SpelExpressionParser expressionParser = new SpelExpressionParser(new SpelParserConfiguration(SpelCompilerMode.IMMEDIATE, null)); Expression expression = expressionParser.parseExpression("#target.process(#root)"); @@ -715,7 +715,7 @@ public void testCompiledExpressionForProxy_SPR16191() { } @Test - public void varargsAndPrimitives_SPR8174() throws Exception { + void varargsAndPrimitives_SPR8174() throws Exception { EvaluationContext emptyEvalContext = new StandardEvaluationContext(); List args = new ArrayList<>(); @@ -763,7 +763,7 @@ public void varargsAndPrimitives_SPR8174() throws Exception { } @Test - public void reservedWords_SPR8228() { + void reservedWords_SPR8228() { // "DIV","EQ","GE","GT","LE","LT","MOD","NE","NOT" @SuppressWarnings("unused") @@ -814,7 +814,7 @@ public Reserver getReserver() { } @Test - public void reservedWordProperties_SPR9862() { + void reservedWordProperties_SPR9862() { StandardEvaluationContext context = new StandardEvaluationContext(); SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expression = parser.parseRaw("T(org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver).CONST"); @@ -829,7 +829,7 @@ public void reservedWordProperties_SPR9862() { * in evaluation of SPEL expressions for a given context. */ @Test - public void propertyAccessorOrder_SPR8211() { + void propertyAccessorOrder_SPR8211() { ExpressionParser expressionParser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new ContextObject()); @@ -849,7 +849,7 @@ public void propertyAccessorOrder_SPR8211() { * determines the set of methods for a type. */ @Test - public void customStaticFunctions_SPR9038() { + void customStaticFunctions_SPR9038() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); List methodResolvers = new ArrayList<>(); @@ -873,7 +873,7 @@ protected Method[] getMethods(Class type) { } @Test - public void array() { + void array() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = null; @@ -902,7 +902,7 @@ public void array() { } @Test - public void SPR9486_floatFunctionResolver() { + void SPR9486_floatFunctionResolver() { Number expectedResult = Math.abs(-10.2f); ExpressionParser parser = new SpelExpressionParser(); SPR9486_FunctionsClass testObject = new SPR9486_FunctionsClass(); @@ -914,7 +914,7 @@ public void SPR9486_floatFunctionResolver() { } @Test - public void SPR9486_addFloatWithDouble() { + void SPR9486_addFloatWithDouble() { Number expectedNumber = 10.21f + 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -924,7 +924,7 @@ public void SPR9486_addFloatWithDouble() { } @Test - public void SPR9486_addFloatWithFloat() { + void SPR9486_addFloatWithFloat() { Number expectedNumber = 10.21f + 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -934,7 +934,7 @@ public void SPR9486_addFloatWithFloat() { } @Test - public void SPR9486_subtractFloatWithDouble() { + void SPR9486_subtractFloatWithDouble() { Number expectedNumber = 10.21f - 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -944,7 +944,7 @@ public void SPR9486_subtractFloatWithDouble() { } @Test - public void SPR9486_subtractFloatWithFloat() { + void SPR9486_subtractFloatWithFloat() { Number expectedNumber = 10.21f - 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -954,7 +954,7 @@ public void SPR9486_subtractFloatWithFloat() { } @Test - public void SPR9486_multiplyFloatWithDouble() { + void SPR9486_multiplyFloatWithDouble() { Number expectedNumber = 10.21f * 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -964,7 +964,7 @@ public void SPR9486_multiplyFloatWithDouble() { } @Test - public void SPR9486_multiplyFloatWithFloat() { + void SPR9486_multiplyFloatWithFloat() { Number expectedNumber = 10.21f * 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -974,7 +974,7 @@ public void SPR9486_multiplyFloatWithFloat() { } @Test - public void SPR9486_floatDivideByFloat() { + void SPR9486_floatDivideByFloat() { Number expectedNumber = -10.21f / -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -984,7 +984,7 @@ public void SPR9486_floatDivideByFloat() { } @Test - public void SPR9486_floatDivideByDouble() { + void SPR9486_floatDivideByDouble() { Number expectedNumber = -10.21f / -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -994,7 +994,7 @@ public void SPR9486_floatDivideByDouble() { } @Test - public void SPR9486_floatEqFloatUnaryMinus() { + void SPR9486_floatEqFloatUnaryMinus() { Boolean expectedResult = -10.21f == -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1004,7 +1004,7 @@ public void SPR9486_floatEqFloatUnaryMinus() { } @Test - public void SPR9486_floatEqDoubleUnaryMinus() { + void SPR9486_floatEqDoubleUnaryMinus() { Boolean expectedResult = -10.21f == -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1014,7 +1014,7 @@ public void SPR9486_floatEqDoubleUnaryMinus() { } @Test - public void SPR9486_floatEqFloat() { + void SPR9486_floatEqFloat() { Boolean expectedResult = 10.215f == 10.2109f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1024,7 +1024,7 @@ public void SPR9486_floatEqFloat() { } @Test - public void SPR9486_floatEqDouble() { + void SPR9486_floatEqDouble() { Boolean expectedResult = 10.215f == 10.2109; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1034,7 +1034,7 @@ public void SPR9486_floatEqDouble() { } @Test - public void SPR9486_floatNotEqFloat() { + void SPR9486_floatNotEqFloat() { Boolean expectedResult = 10.215f != 10.2109f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1044,7 +1044,7 @@ public void SPR9486_floatNotEqFloat() { } @Test - public void SPR9486_floatNotEqDouble() { + void SPR9486_floatNotEqDouble() { Boolean expectedResult = 10.215f != 10.2109; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1054,7 +1054,7 @@ public void SPR9486_floatNotEqDouble() { } @Test - public void SPR9486_floatLessThanFloat() { + void SPR9486_floatLessThanFloat() { Boolean expectedNumber = -10.21f < -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1064,7 +1064,7 @@ public void SPR9486_floatLessThanFloat() { } @Test - public void SPR9486_floatLessThanDouble() { + void SPR9486_floatLessThanDouble() { Boolean expectedNumber = -10.21f < -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1074,7 +1074,7 @@ public void SPR9486_floatLessThanDouble() { } @Test - public void SPR9486_floatLessThanOrEqualFloat() { + void SPR9486_floatLessThanOrEqualFloat() { Boolean expectedNumber = -10.21f <= -10.22f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1084,7 +1084,7 @@ public void SPR9486_floatLessThanOrEqualFloat() { } @Test - public void SPR9486_floatLessThanOrEqualDouble() { + void SPR9486_floatLessThanOrEqualDouble() { Boolean expectedNumber = -10.21f <= -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1094,7 +1094,7 @@ public void SPR9486_floatLessThanOrEqualDouble() { } @Test - public void SPR9486_floatGreaterThanFloat() { + void SPR9486_floatGreaterThanFloat() { Boolean expectedNumber = -10.21f > -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1104,7 +1104,7 @@ public void SPR9486_floatGreaterThanFloat() { } @Test - public void SPR9486_floatGreaterThanDouble() { + void SPR9486_floatGreaterThanDouble() { Boolean expectedResult = -10.21f > -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1114,7 +1114,7 @@ public void SPR9486_floatGreaterThanDouble() { } @Test - public void SPR9486_floatGreaterThanOrEqualFloat() { + void SPR9486_floatGreaterThanOrEqualFloat() { Boolean expectedNumber = -10.21f >= -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1124,7 +1124,7 @@ public void SPR9486_floatGreaterThanOrEqualFloat() { } @Test - public void SPR9486_floatGreaterThanEqualDouble() { + void SPR9486_floatGreaterThanEqualDouble() { Boolean expectedResult = -10.21f >= -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1134,7 +1134,7 @@ public void SPR9486_floatGreaterThanEqualDouble() { } @Test - public void SPR9486_floatModulusFloat() { + void SPR9486_floatModulusFloat() { Number expectedResult = 10.21f % 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1144,7 +1144,7 @@ public void SPR9486_floatModulusFloat() { } @Test - public void SPR9486_floatModulusDouble() { + void SPR9486_floatModulusDouble() { Number expectedResult = 10.21f % 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1154,7 +1154,7 @@ public void SPR9486_floatModulusDouble() { } @Test - public void SPR9486_floatPowerFloat() { + void SPR9486_floatPowerFloat() { Number expectedResult = Math.pow(10.21f, -10.2f); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1164,7 +1164,7 @@ public void SPR9486_floatPowerFloat() { } @Test - public void SPR9486_floatPowerDouble() { + void SPR9486_floatPowerDouble() { Number expectedResult = Math.pow(10.21f, 10.2); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); @@ -1174,7 +1174,7 @@ public void SPR9486_floatPowerDouble() { } @Test - public void SPR9994_bridgeMethods() throws Exception { + void SPR9994_bridgeMethods() throws Exception { ReflectivePropertyAccessor accessor = new ReflectivePropertyAccessor(); StandardEvaluationContext context = new StandardEvaluationContext(); GenericImplementation target = new GenericImplementation(); @@ -1187,7 +1187,7 @@ public void SPR9994_bridgeMethods() throws Exception { } @Test - public void SPR10162_onlyBridgeMethod() throws Exception { + void SPR10162_onlyBridgeMethod() throws Exception { ReflectivePropertyAccessor accessor = new ReflectivePropertyAccessor(); StandardEvaluationContext context = new StandardEvaluationContext(); Object target = new OnlyBridgeMethod(); @@ -1197,7 +1197,7 @@ public void SPR10162_onlyBridgeMethod() throws Exception { } @Test - public void SPR10091_simpleTestValueType() { + void SPR10091_simpleTestValueType() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Class valueType = parser.parseExpression("simpleProperty").getValueType(evaluationContext); @@ -1205,7 +1205,7 @@ public void SPR10091_simpleTestValueType() { } @Test - public void SPR10091_simpleTestValue() { + void SPR10091_simpleTestValue() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Object value = parser.parseExpression("simpleProperty").getValue(evaluationContext); @@ -1213,7 +1213,7 @@ public void SPR10091_simpleTestValue() { } @Test - public void SPR10091_primitiveTestValueType() { + void SPR10091_primitiveTestValueType() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Class valueType = parser.parseExpression("primitiveProperty").getValueType(evaluationContext); @@ -1221,7 +1221,7 @@ public void SPR10091_primitiveTestValueType() { } @Test - public void SPR10091_primitiveTestValue() { + void SPR10091_primitiveTestValue() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Object value = parser.parseExpression("primitiveProperty").getValue(evaluationContext); @@ -1229,7 +1229,7 @@ public void SPR10091_primitiveTestValue() { } @Test - public void SPR16123() { + void SPR16123() { ExpressionParser parser = new SpelExpressionParser(); parser.parseExpression("simpleProperty").setValue(new BooleanHolder(), null); assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> @@ -1237,7 +1237,7 @@ public void SPR16123() { } @Test - public void SPR10146_malformedExpressions() { + void SPR10146_malformedExpressions() { doTestSpr10146("/foo", "EL1070E: Problem parsing left operand"); doTestSpr10146("*foo", "EL1070E: Problem parsing left operand"); doTestSpr10146("%foo", "EL1070E: Problem parsing left operand"); @@ -1255,7 +1255,7 @@ private void doTestSpr10146(String expression, String expectedMessage) { } @Test - public void SPR10125() { + void SPR10125() { StandardEvaluationContext context = new StandardEvaluationContext(); String fromInterface = parser.parseExpression("T(" + StaticFinalImpl1.class.getName() + ").VALUE").getValue( context, String.class); @@ -1266,7 +1266,7 @@ public void SPR10125() { } @Test - public void SPR10210() { + void SPR10210() { StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("bridgeExample", new org.springframework.expression.spel.spr10210.D()); Expression parseExpression = parser.parseExpression("#bridgeExample.bridgeMethod()"); @@ -1274,14 +1274,14 @@ public void SPR10210() { } @Test - public void SPR10328() { + void SPR10328() { assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> parser.parseExpression("$[]")) .withMessageContaining("EL1071E: A required selection expression has not been specified"); } @Test - public void SPR10452() { + void SPR10452() { SpelParserConfiguration configuration = new SpelParserConfiguration(false, false); ExpressionParser parser = new SpelExpressionParser(configuration); @@ -1306,7 +1306,7 @@ public void SPR10452() { } @Test - public void SPR9495() { + void SPR9495() { SpelParserConfiguration configuration = new SpelParserConfiguration(false, false); ExpressionParser parser = new SpelExpressionParser(configuration); @@ -1347,7 +1347,7 @@ public MethodExecutor resolve(EvaluationContext context, Object targetObject, St } @Test - public void SPR10486() { + void SPR10486() { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); Spr10486 rootObject = new Spr10486(); @@ -1358,7 +1358,7 @@ public void SPR10486() { } @Test - public void SPR11142() { + void SPR11142() { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); Spr11142 rootObject = new Spr11142(); @@ -1369,7 +1369,7 @@ public void SPR11142() { } @Test - public void SPR9194() { + void SPR9194() { TestClass2 one = new TestClass2("abc"); TestClass2 two = new TestClass2("abc"); Map map = new HashMap<>(); @@ -1382,7 +1382,7 @@ public void SPR9194() { } @Test - public void SPR11348() { + void SPR11348() { Collection coll = new LinkedHashSet<>(); coll.add("one"); coll.add("two"); @@ -1399,14 +1399,14 @@ public void SPR11348() { } @Test - public void SPR11445_simple() { + void SPR11445_simple() { StandardEvaluationContext context = new StandardEvaluationContext(new Spr11445Class()); Expression expr = new SpelExpressionParser().parseRaw("echo(parameter())"); assertThat(expr.getValue(context)).isEqualTo(1); } @Test - public void SPR11445_beanReference() { + void SPR11445_beanReference() { StandardEvaluationContext context = new StandardEvaluationContext(); context.setBeanResolver(new Spr11445Class()); Expression expr = new SpelExpressionParser().parseRaw("@bean.echo(@bean.parameter())"); @@ -1415,14 +1415,14 @@ public void SPR11445_beanReference() { @Test @SuppressWarnings("unchecked") - public void SPR11494() { + void SPR11494() { Expression exp = new SpelExpressionParser().parseExpression("T(java.util.Arrays).asList('a','b')"); List list = (List) exp.getValue(); assertThat(list).hasSize(2); } @Test - public void SPR11609() { + void SPR11609() { StandardEvaluationContext sec = new StandardEvaluationContext(); sec.addPropertyAccessor(new MapAccessor()); Expression exp = new SpelExpressionParser().parseExpression( @@ -1431,7 +1431,7 @@ public void SPR11609() { } @Test - public void SPR9735() { + void SPR9735() { Item item = new Item(); item.setName("parent"); @@ -1453,7 +1453,7 @@ public void SPR9735() { } @Test - public void SPR12502() { + void SPR12502() { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("#root.getClass().getName()"); assertThat(expression.getValue(new UnnamedUser())).isEqualTo(UnnamedUser.class.getName()); @@ -1462,7 +1462,7 @@ public void SPR12502() { @Test @SuppressWarnings("rawtypes") - public void SPR12522() { + void SPR12522() { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("T(java.util.Arrays).asList('')"); Object value = expression.getValue(); @@ -1471,7 +1471,7 @@ public void SPR12522() { } @Test - public void SPR12803() { + void SPR12803() { StandardEvaluationContext sec = new StandardEvaluationContext(); sec.setVariable("iterable", Collections.emptyList()); SpelExpressionParser parser = new SpelExpressionParser(); @@ -1480,7 +1480,7 @@ public void SPR12803() { } @Test - public void SPR12808() { + void SPR12808() { SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("T(org.springframework.expression.spel.SpelReproTests.DistanceEnforcer).from(#no)"); StandardEvaluationContext sec = new StandardEvaluationContext(); @@ -1496,7 +1496,7 @@ public void SPR12808() { @Test @SuppressWarnings("rawtypes") - public void SPR13055() { + void SPR13055() { List> myPayload = new ArrayList<>(); Map v1 = new HashMap<>(); @@ -1527,7 +1527,7 @@ public void SPR13055() { } @Test - public void AccessingFactoryBean_spr9511() { + void AccessingFactoryBean_spr9511() { StandardEvaluationContext context = new StandardEvaluationContext(); context.setBeanResolver(new MyBeanResolver()); Expression expr = new SpelExpressionParser().parseRaw("@foo"); @@ -1551,7 +1551,7 @@ public void AccessingFactoryBean_spr9511() { } @Test - public void SPR12035() { + void SPR12035() { ExpressionParser parser = new SpelExpressionParser(); Expression expression1 = parser.parseExpression("list.?[ value>2 ].size()!=0"); @@ -1562,7 +1562,7 @@ public void SPR12035() { } @Test - public void SPR13055_maps() { + void SPR13055_maps() { EvaluationContext context = new StandardEvaluationContext(); ExpressionParser parser = new SpelExpressionParser(); @@ -1578,7 +1578,7 @@ public void SPR13055_maps() { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void SPR10417() { + void SPR10417() { List list1 = new ArrayList(); list1.add("a"); list1.add("b"); @@ -1619,7 +1619,7 @@ public void SPR10417() { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void SPR10417_maps() { + void SPR10417_maps() { Map map1 = new HashMap(); map1.put("A", 65); map1.put("B", 66); @@ -1642,7 +1642,7 @@ public void SPR10417_maps() { } @Test - public void SPR13918() { + void SPR13918() { EvaluationContext context = new StandardEvaluationContext(); context.setVariable("encoding", "UTF-8"); @@ -1652,7 +1652,7 @@ public void SPR13918() { } @Test - public void SPR16032() { + void SPR16032() { EvaluationContext context = new StandardEvaluationContext(); context.setVariable("str", "a\0b"); diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java index f78a8d13fe3c..d4140d33e183 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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,7 @@ * @author Juergen Hoeller * @author Chris Beams */ -public class MessageListenerAdapterTests { +class MessageListenerAdapterTests { private static final String TEXT = "I fancy a good cuppa right now"; @@ -65,7 +65,7 @@ public class MessageListenerAdapterTests { @Test - public void testWithMessageContentsDelegateForTextMessage() throws Exception { + void testWithMessageContentsDelegateForTextMessage() throws Exception { TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... given(textMessage.getText()).willReturn(TEXT); @@ -79,17 +79,14 @@ public void testWithMessageContentsDelegateForTextMessage() throws Exception { } @Test - public void testWithMessageContentsDelegateForBytesMessage() throws Exception { + void testWithMessageContentsDelegateForBytesMessage() throws Exception { BytesMessage bytesMessage = mock(BytesMessage.class); // BytesMessage contents must be unwrapped... - given(bytesMessage.getBodyLength()).willReturn(new Long(TEXT.getBytes().length)); - given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - byte[] bytes = (byte[]) invocation.getArguments()[0]; - ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); - return inputStream.read(bytes); - } + given(bytesMessage.getBodyLength()).willReturn(Long.valueOf(TEXT.getBytes().length)); + given(bytesMessage.readBytes(any(byte[].class))).willAnswer((Answer) invocation -> { + byte[] bytes = (byte[]) invocation.getArguments()[0]; + ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); + return inputStream.read(bytes); }); MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); @@ -101,7 +98,7 @@ public Integer answer(InvocationOnMock invocation) throws Throwable { } @Test - public void testWithMessageContentsDelegateForObjectMessage() throws Exception { + void testWithMessageContentsDelegateForObjectMessage() throws Exception { ObjectMessage objectMessage = mock(ObjectMessage.class); given(objectMessage.getObject()).willReturn(NUMBER); @@ -114,7 +111,7 @@ public void testWithMessageContentsDelegateForObjectMessage() throws Exception { } @Test - public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception { + void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception { ObjectMessage objectMessage = mock(ObjectMessage.class); given(objectMessage.getObject()).willReturn(OBJECT); @@ -127,7 +124,7 @@ public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() thr } @Test - public void testWithMessageDelegate() throws Exception { + void testWithMessageDelegate() throws Exception { TextMessage textMessage = mock(TextMessage.class); MessageDelegate delegate = mock(MessageDelegate.class); @@ -141,7 +138,7 @@ public void testWithMessageDelegate() throws Exception { } @Test - public void testWhenTheAdapterItselfIsTheDelegate() throws Exception { + void testWhenTheAdapterItselfIsTheDelegate() throws Exception { TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... given(textMessage.getText()).willReturn(TEXT); @@ -152,7 +149,7 @@ public void testWhenTheAdapterItselfIsTheDelegate() throws Exception { } @Test - public void testRainyDayWithNoApplicableHandlingMethods() throws Exception { + void testRainyDayWithNoApplicableHandlingMethods() throws Exception { TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... given(textMessage.getText()).willReturn(TEXT); @@ -164,7 +161,7 @@ public void testRainyDayWithNoApplicableHandlingMethods() throws Exception { } @Test - public void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception { + void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception { final IllegalArgumentException exception = new IllegalArgumentException(); TextMessage textMessage = mock(TextMessage.class); @@ -189,7 +186,7 @@ protected void handleListenerException(Throwable ex) { } @Test - public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception { + void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception { MessageListenerAdapter adapter = new MessageListenerAdapter(); assertThat(adapter.getMessageConverter()).as("The default [MessageConverter] must never be null.").isNotNull(); boolean condition = adapter.getMessageConverter() instanceof SimpleMessageConverter; @@ -197,19 +194,19 @@ public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter( } @Test - public void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception { + void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception { MessageListenerAdapter adapter = new MessageListenerAdapter(); assertThat(adapter.getDelegate()).isSameAs(adapter); } @Test - public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception { + void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception { MessageListenerAdapter adapter = new MessageListenerAdapter(); assertThat(adapter.getDefaultListenerMethod()).isEqualTo(MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD); } @Test - public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception { + void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception { TextMessage textMessage = mock(TextMessage.class); ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); given(delegate.handleMessage(textMessage)).willReturn(TEXT); @@ -221,7 +218,7 @@ public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSe } @Test - public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { + void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { Queue destination = mock(Queue.class); TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... @@ -256,7 +253,7 @@ protected Object extractMessage(Message message) { } @Test - public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { + void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { Queue destination = mock(Queue.class); TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... @@ -289,7 +286,7 @@ protected Object extractMessage(Message message) { } @Test - public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { + void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); @@ -318,7 +315,7 @@ protected Object extractMessage(Message message) { } @Test - public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception { + void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception { Queue destination = mock(Queue.class); final TextMessage sentTextMessage = mock(TextMessage.class); @@ -354,7 +351,7 @@ protected Object extractMessage(Message message) { } @Test - public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception { + void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception { final TextMessage message = mock(TextMessage.class); final QueueSession session = mock(QueueSession.class); @@ -372,7 +369,7 @@ protected Object extractMessage(Message message) { } @Test - public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { + void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { final TextMessage sentTextMessage = mock(TextMessage.class); final Session session = mock(Session.class); ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); @@ -391,7 +388,7 @@ protected Object extractMessage(Message message) { } @Test - public void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { + void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { Queue destination = mock(Queue.class); final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java index a7942cccb8e0..2d2b48fbfb41 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -49,7 +49,7 @@ * @author Dave Syer * @author Stephane Nicoll */ -public class MappingJackson2MessageConverterTests { +class MappingJackson2MessageConverterTests { private MappingJackson2MessageConverter converter; @@ -66,7 +66,7 @@ public void setup() { @Test - public void toBytesMessage() throws Exception { + void toBytesMessage() throws Exception { BytesMessage bytesMessageMock = mock(BytesMessage.class); Date toBeMarshalled = new Date(); @@ -80,7 +80,7 @@ public void toBytesMessage() throws Exception { } @Test - public void fromBytesMessage() throws Exception { + void fromBytesMessage() throws Exception { BytesMessage bytesMessageMock = mock(BytesMessage.class); Map unmarshalled = Collections.singletonMap("foo", "bar"); @@ -89,21 +89,16 @@ public void fromBytesMessage() throws Exception { given(bytesMessageMock.getStringProperty("__typeid__")).willReturn(Object.class.getName()); given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); - given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length)); + given(bytesMessageMock.getBodyLength()).willReturn(Long.valueOf(bytes.length)); given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( - new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - return byteStream.read((byte[]) invocation.getArguments()[0]); - } - }); + (Answer) invocation -> byteStream.read((byte[]) invocation.getArguments()[0])); Object result = converter.fromMessage(bytesMessageMock); assertThat(unmarshalled).as("Invalid result").isEqualTo(result); } @Test - public void toTextMessageWithObject() throws Exception { + void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(TextMessage.class); Date toBeMarshalled = new Date(); @@ -115,7 +110,7 @@ public void toTextMessageWithObject() throws Exception { } @Test - public void toTextMessageWithMap() throws Exception { + void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(TextMessage.class); Map toBeMarshalled = new HashMap<>(); @@ -128,7 +123,7 @@ public void toTextMessageWithMap() throws Exception { } @Test - public void fromTextMessage() throws Exception { + void fromTextMessage() throws Exception { TextMessage textMessageMock = mock(TextMessage.class); MyBean unmarshalled = new MyBean("bar"); @@ -141,7 +136,7 @@ public void fromTextMessage() throws Exception { } @Test - public void fromTextMessageWithUnknownProperty() throws Exception { + void fromTextMessageWithUnknownProperty() throws Exception { TextMessage textMessageMock = mock(TextMessage.class); MyBean unmarshalled = new MyBean("bar"); @@ -154,7 +149,7 @@ public void fromTextMessageWithUnknownProperty() throws Exception { } @Test - public void fromTextMessageAsObject() throws Exception { + void fromTextMessageAsObject() throws Exception { TextMessage textMessageMock = mock(TextMessage.class); Map unmarshalled = Collections.singletonMap("foo", "bar"); @@ -167,7 +162,7 @@ public void fromTextMessageAsObject() throws Exception { } @Test - public void fromTextMessageAsMap() throws Exception { + void fromTextMessageAsMap() throws Exception { TextMessage textMessageMock = mock(TextMessage.class); Map unmarshalled = Collections.singletonMap("foo", "bar"); @@ -180,7 +175,7 @@ public void fromTextMessageAsMap() throws Exception { } @Test - public void toTextMessageWithReturnType() throws JMSException, NoSuchMethodException { + void toTextMessageWithReturnType() throws JMSException, NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("summary"); MethodParameter returnType = new MethodParameter(method, -1); testToTextMessageWithReturnType(returnType); @@ -188,13 +183,13 @@ public void toTextMessageWithReturnType() throws JMSException, NoSuchMethodExcep } @Test - public void toTextMessageWithNullReturnType() throws JMSException, NoSuchMethodException { + void toTextMessageWithNullReturnType() throws JMSException, NoSuchMethodException { testToTextMessageWithReturnType(null); verify(sessionMock).createTextMessage("{\"name\":\"test\",\"description\":\"lengthy description\"}"); } @Test - public void toTextMessageWithReturnTypeAndNoJsonView() throws JMSException, NoSuchMethodException { + void toTextMessageWithReturnTypeAndNoJsonView() throws JMSException, NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("none"); MethodParameter returnType = new MethodParameter(method, -1); @@ -203,7 +198,7 @@ public void toTextMessageWithReturnTypeAndNoJsonView() throws JMSException, NoSu } @Test - public void toTextMessageWithReturnTypeAndMultipleJsonViews() throws JMSException, NoSuchMethodException { + void toTextMessageWithReturnTypeAndMultipleJsonViews() throws JMSException, NoSuchMethodException { Method method = this.getClass().getDeclaredMethod("invalid"); MethodParameter returnType = new MethodParameter(method, -1); @@ -222,7 +217,7 @@ private void testToTextMessageWithReturnType(MethodParameter returnType) throws } @Test - public void toTextMessageWithJsonViewClass() throws JMSException { + void toTextMessageWithJsonViewClass() throws JMSException { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(TextMessage.class); @@ -236,7 +231,7 @@ public void toTextMessageWithJsonViewClass() throws JMSException { } @Test - public void toTextMessageWithAnotherJsonViewClass() throws JMSException { + void toTextMessageWithAnotherJsonViewClass() throws JMSException { converter.setTargetType(MessageType.TEXT); TextMessage textMessageMock = mock(TextMessage.class); diff --git a/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java b/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java index 80e098ba1301..644086ebf784 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java @@ -83,7 +83,7 @@ public void testEscapedErrors() { FieldError ageError = errors.getFieldError("age"); assertThat("message: <tag>".equals(ageError.getDefaultMessage())).as("Age error message escaped").isTrue(); assertThat("AGE_NOT_SET ".equals(ageError.getCode())).as("Age error code not escaped").isTrue(); - assertThat((new Integer(0)).equals(errors.getFieldValue("age"))).as("Age value not escaped").isTrue(); + assertThat((Integer.valueOf(0)).equals(errors.getFieldValue("age"))).as("Age value not escaped").isTrue(); FieldError ageErrorInList = errors.getFieldErrors("age").get(0); assertThat(ageError.getDefaultMessage().equals(ageErrorInList.getDefaultMessage())).as("Same name error in list").isTrue(); FieldError ageError2 = errors.getFieldErrors("age").get(1); diff --git a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java index d0f108eb9d7e..00a82790f3b6 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -47,7 +47,7 @@ void testIntParameter() throws ServletRequestBindingException { assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameter(request, "param2")); - assertThat(ServletRequestUtils.getIntParameter(request, "param3")).isEqualTo(null); + assertThat(ServletRequestUtils.getIntParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getIntParameter(request, "param3", 6)).isEqualTo(6); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameter(request, "param3")); @@ -66,7 +66,7 @@ void testIntParameters() throws ServletRequestBindingException { int[] array = new int[] {1, 2, 3}; int[] values = ServletRequestUtils.getRequiredIntParameters(request, "param"); - assertThat(3).isEqualTo(values.length); + assertThat(values).hasSize(3); for (int i = 0; i < array.length; i++) { assertThat(array[i]).isEqualTo(values[i]); } @@ -81,7 +81,7 @@ void testLongParameter() throws ServletRequestBindingException { request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); - assertThat(ServletRequestUtils.getLongParameter(request, "param1")).isEqualTo(new Long(5L)); + assertThat(ServletRequestUtils.getLongParameter(request, "param1")).isEqualTo(Long.valueOf(5L)); assertThat(ServletRequestUtils.getLongParameter(request, "param1", 6L)).isEqualTo(5L); assertThat(ServletRequestUtils.getRequiredIntParameter(request, "param1")).isEqualTo(5L); @@ -89,7 +89,7 @@ void testLongParameter() throws ServletRequestBindingException { assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameter(request, "param2")); - assertThat(ServletRequestUtils.getLongParameter(request, "param3")).isEqualTo(null); + assertThat(ServletRequestUtils.getLongParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getLongParameter(request, "param3", 6L)).isEqualTo(6L); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameter(request, "param3")); @@ -128,7 +128,7 @@ void testFloatParameter() throws ServletRequestBindingException { request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); - assertThat(ServletRequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f))).isTrue(); + assertThat(ServletRequestUtils.getFloatParameter(request, "param1")).isEqualTo(Float.valueOf(5.5f)); assertThat(ServletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f).isTrue(); assertThat(ServletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f).isTrue(); @@ -136,7 +136,7 @@ void testFloatParameter() throws ServletRequestBindingException { assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param2")); - assertThat(ServletRequestUtils.getFloatParameter(request, "param3") == null).isTrue(); + assertThat(ServletRequestUtils.getFloatParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param3")); @@ -166,7 +166,7 @@ void testDoubleParameter() throws ServletRequestBindingException { request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); - assertThat(ServletRequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5))).isTrue(); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param1")).isEqualTo(Double.valueOf(5.5)); assertThat(ServletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5).isTrue(); assertThat(ServletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5).isTrue(); @@ -174,7 +174,7 @@ void testDoubleParameter() throws ServletRequestBindingException { assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param2")); - assertThat(ServletRequestUtils.getDoubleParameter(request, "param3") == null).isTrue(); + assertThat(ServletRequestUtils.getDoubleParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param3")); @@ -212,7 +212,7 @@ void testBooleanParameter() throws ServletRequestBindingException { assertThat(ServletRequestUtils.getBooleanParameter(request, "param2", true)).isFalse(); assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param2")).isFalse(); - assertThat(ServletRequestUtils.getBooleanParameter(request, "param3") == null).isTrue(); + assertThat(ServletRequestUtils.getBooleanParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getBooleanParameter(request, "param3", true)).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredBooleanParameter(request, "param3")); @@ -235,14 +235,14 @@ void testBooleanParameters() throws ServletRequestBindingException { boolean[] array = new boolean[] {true, true, false, true, false}; boolean[] values = ServletRequestUtils.getRequiredBooleanParameters(request, "param"); - assertThat(array.length).isEqualTo(values.length); + assertThat(array).hasSameSizeAs(values); for (int i = 0; i < array.length; i++) { assertThat(array[i]).isEqualTo(values[i]); } array = new boolean[] {false, true, false}; values = ServletRequestUtils.getRequiredBooleanParameters(request, "param2"); - assertThat(array.length).isEqualTo(values.length); + assertThat(array).hasSameSizeAs(values); for (int i = 0; i < array.length; i++) { assertThat(array[i]).isEqualTo(values[i]); } diff --git a/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java b/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java index 256b9631df72..9549902149ec 100644 --- a/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java +++ b/spring-web/src/test/java/org/springframework/web/cors/CorsConfigurationTests.java @@ -33,10 +33,10 @@ * @author Sebastien Deleuze * @author Sam Brannen */ -public class CorsConfigurationTests { +class CorsConfigurationTests { @Test - public void setNullValues() { + void setNullValues() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(null); assertThat(config.getAllowedOrigins()).isNull(); @@ -55,7 +55,7 @@ public void setNullValues() { } @Test - public void setValues() { + void setValues() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedOriginPattern("http://*.example.com"); @@ -71,11 +71,11 @@ public void setValues() { assertThat(config.getAllowedMethods()).containsExactly("*"); assertThat(config.getExposedHeaders()).containsExactly("*"); assertThat(config.getAllowCredentials()).isTrue(); - assertThat(config.getMaxAge()).isEqualTo(new Long(123)); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(123)); } @Test - public void combineWithNull() { + void combineWithNull() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Collections.singletonList("*")); config.combine(null); @@ -84,7 +84,7 @@ public void combineWithNull() { } @Test - public void combineWithNullProperties() { + void combineWithNullProperties() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.setAllowedOriginPatterns(Collections.singletonList("http://*.example.com")); @@ -103,12 +103,12 @@ public void combineWithNullProperties() { assertThat(config.getAllowedHeaders()).containsExactly("header1"); assertThat(config.getExposedHeaders()).containsExactly("header3"); assertThat(config.getAllowedMethods()).containsExactly(HttpMethod.GET.name()); - assertThat(config.getMaxAge()).isEqualTo(new Long(123)); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(123)); assertThat(config.getAllowCredentials()).isTrue(); } @Test // SPR-15772 - public void combineWithDefaultPermitValues() { + void combineWithDefaultPermitValues() { CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues(); CorsConfiguration other = new CorsConfiguration(); other.addAllowedOrigin("https://domain.com"); @@ -147,7 +147,7 @@ public void combineWithDefaultPermitValues() { } @Test - public void combinePatternWithDefaultPermitValues() { + void combinePatternWithDefaultPermitValues() { CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues(); CorsConfiguration other = new CorsConfiguration(); other.addAllowedOriginPattern("http://*.com"); @@ -164,7 +164,7 @@ public void combinePatternWithDefaultPermitValues() { } @Test - public void combinePatternWithDefaultPermitValuesAndCustomOrigin() { + void combinePatternWithDefaultPermitValuesAndCustomOrigin() { CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues(); config.setAllowedOrigins(Collections.singletonList("https://domain.com")); @@ -183,7 +183,7 @@ public void combinePatternWithDefaultPermitValuesAndCustomOrigin() { } @Test - public void combineWithAsteriskWildCard() { + void combineWithAsteriskWildCard() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); @@ -219,7 +219,7 @@ public void combineWithAsteriskWildCard() { } @Test // SPR-14792 - public void combineWithDuplicatedElements() { + void combineWithDuplicatedElements() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("https://domain1.com"); config.addAllowedOrigin("https://domain2.com"); @@ -249,7 +249,7 @@ public void combineWithDuplicatedElements() { } @Test - public void combine() { + void combine() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("https://domain1.com"); config.addAllowedOriginPattern("http://*.domain1.com"); @@ -274,14 +274,14 @@ public void combine() { assertThat(config.getAllowedHeaders()).containsExactly("header1", "header2"); assertThat(config.getExposedHeaders()).containsExactly("header3", "header4"); assertThat(config.getAllowedMethods()).containsExactly(HttpMethod.GET.name(), HttpMethod.PUT.name()); - assertThat(config.getMaxAge()).isEqualTo(new Long(456)); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(456)); assertThat(config).isNotNull(); assertThat(config.getAllowCredentials()).isFalse(); assertThat(config.getAllowedOriginPatterns()).containsExactly("http://*.domain1.com", "http://*.domain2.com"); } @Test - public void checkOriginAllowed() { + void checkOriginAllowed() { // "*" matches CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); @@ -306,7 +306,7 @@ public void checkOriginAllowed() { } @Test - public void checkOriginNotAllowed() { + void checkOriginNotAllowed() { CorsConfiguration config = new CorsConfiguration(); assertThat(config.checkOrigin(null)).isNull(); assertThat(config.checkOrigin("https://domain.com")).isNull(); @@ -322,7 +322,7 @@ public void checkOriginNotAllowed() { } @Test - public void checkOriginPatternAllowed() { + void checkOriginPatternAllowed() { CorsConfiguration config = new CorsConfiguration(); assertThat(config.checkOrigin("https://domain.com")).isNull(); @@ -349,7 +349,7 @@ public void checkOriginPatternAllowed() { } @Test - public void checkOriginPatternNotAllowed() { + void checkOriginPatternNotAllowed() { CorsConfiguration config = new CorsConfiguration(); assertThat(config.checkOrigin(null)).isNull(); assertThat(config.checkOrigin("https://domain.com")).isNull(); @@ -367,7 +367,7 @@ public void checkOriginPatternNotAllowed() { } @Test - public void checkMethodAllowed() { + void checkMethodAllowed() { CorsConfiguration config = new CorsConfiguration(); assertThat(config.checkHttpMethod(HttpMethod.GET)).containsExactly(HttpMethod.GET, HttpMethod.HEAD); @@ -380,7 +380,7 @@ public void checkMethodAllowed() { } @Test - public void checkMethodNotAllowed() { + void checkMethodNotAllowed() { CorsConfiguration config = new CorsConfiguration(); assertThat(config.checkHttpMethod(null)).isNull(); assertThat(config.checkHttpMethod(HttpMethod.DELETE)).isNull(); @@ -390,7 +390,7 @@ public void checkMethodNotAllowed() { } @Test - public void checkHeadersAllowed() { + void checkHeadersAllowed() { CorsConfiguration config = new CorsConfiguration(); assertThat(config.checkHeaders(Collections.emptyList())).isEqualTo(Collections.emptyList()); @@ -403,7 +403,7 @@ public void checkHeadersAllowed() { } @Test - public void checkHeadersNotAllowed() { + void checkHeadersNotAllowed() { CorsConfiguration config = new CorsConfiguration(); assertThat(config.checkHeaders(null)).isNull(); assertThat(config.checkHeaders(Collections.singletonList("header1"))).isNull(); @@ -417,7 +417,7 @@ public void checkHeadersNotAllowed() { } @Test // SPR-15772 - public void changePermitDefaultValues() { + void changePermitDefaultValues() { CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues(); config.addAllowedOrigin("https://domain.com"); config.addAllowedHeader("header1"); @@ -429,7 +429,7 @@ public void changePermitDefaultValues() { } @Test - public void permitDefaultDoesntSetOriginWhenPatternPresent() { + void permitDefaultDoesntSetOriginWhenPatternPresent() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOriginPattern("http://*.com"); config = config.applyPermitDefaultValues(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java index 3f1fce6612a2..f4fa67d7ce8a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/CrossOriginTests.java @@ -159,7 +159,7 @@ void defaultAnnotation(TestRequestMappingInfoHandlerMapping mapping) throws Exce assertThat(config.getAllowCredentials()).isNull(); assertThat(config.getAllowedHeaders()).containsExactly("*"); assertThat(CollectionUtils.isEmpty(config.getExposedHeaders())).isTrue(); - assertThat(config.getMaxAge()).isEqualTo(new Long(1800)); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(1800)); } @PathPatternsParameterizedTest @@ -173,7 +173,7 @@ void customized(TestRequestMappingInfoHandlerMapping mapping) throws Exception { assertThat(config.getAllowedOrigins()).containsExactly("https://site1.com", "https://site2.com"); assertThat(config.getAllowedHeaders()).containsExactly("header1", "header2"); assertThat(config.getExposedHeaders()).containsExactly("header3", "header4"); - assertThat(config.getMaxAge()).isEqualTo(new Long(123)); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(123)); assertThat(config.getAllowCredentials()).isFalse(); } @@ -315,7 +315,7 @@ void preFlightRequest(TestRequestMappingInfoHandlerMapping mapping) throws Excep assertThat(config.getAllowCredentials()).isNull(); assertThat(config.getAllowedHeaders()).containsExactly("*"); assertThat(CollectionUtils.isEmpty(config.getExposedHeaders())).isTrue(); - assertThat(config.getMaxAge()).isEqualTo(new Long(1800)); + assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(1800)); } @PathPatternsParameterizedTest @@ -389,7 +389,7 @@ private CorsConfiguration getCorsConfiguration(@Nullable HandlerExecutionChain c assertThat(chain).isNotNull(); if (isPreFlightRequest) { Object handler = chain.getHandler(); - assertThat(handler.getClass().getSimpleName().equals("PreFlightHandler")).isTrue(); + assertThat(handler.getClass().getSimpleName()).isEqualTo("PreFlightHandler"); DirectFieldAccessor accessor = new DirectFieldAccessor(handler); return (CorsConfiguration)accessor.getPropertyValue("config"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java index 9e8da5248e67..41ee86b09401 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -38,7 +38,7 @@ * @author Rossen Stoyanchev * @since 3.1 */ -public class RedirectAttributesModelMapTests { +class RedirectAttributesModelMapTests { private RedirectAttributesModelMap redirectAttributes; @@ -54,13 +54,13 @@ public void setup() { } @Test - public void addAttributePrimitiveType() { + void addAttributePrimitiveType() { this.redirectAttributes.addAttribute("speed", 65); assertThat(this.redirectAttributes.get("speed")).isEqualTo("65"); } @Test - public void addAttributeCustomType() { + void addAttributeCustomType() { String attrName = "person"; this.redirectAttributes.addAttribute(attrName, new TestBean("Fred")); @@ -73,7 +73,7 @@ public void addAttributeCustomType() { } @Test - public void addAttributeToString() { + void addAttributeToString() { String attrName = "person"; RedirectAttributesModelMap model = new RedirectAttributesModelMap(); model.addAttribute(attrName, new TestBean("Fred")); @@ -82,22 +82,22 @@ public void addAttributeToString() { } @Test - public void addAttributeValue() { + void addAttributeValue() { this.redirectAttributes.addAttribute(new TestBean("Fred")); assertThat(this.redirectAttributes.get("testBean")).isEqualTo("Fred"); } @Test - public void addAllAttributesList() { - this.redirectAttributes.addAllAttributes(Arrays.asList(new TestBean("Fred"), new Integer(5))); + void addAllAttributesList() { + this.redirectAttributes.addAllAttributes(Arrays.asList(new TestBean("Fred"), 5)); assertThat(this.redirectAttributes.get("testBean")).isEqualTo("Fred"); assertThat(this.redirectAttributes.get("integer")).isEqualTo("5"); } @Test - public void addAttributesMap() { + void addAttributesMap() { Map map = new HashMap<>(); map.put("person", new TestBean("Fred")); map.put("age", 33); @@ -108,7 +108,7 @@ public void addAttributesMap() { } @Test - public void mergeAttributes() { + void mergeAttributes() { Map map = new HashMap<>(); map.put("person", new TestBean("Fred")); map.put("age", 33); @@ -121,14 +121,14 @@ public void mergeAttributes() { } @Test - public void put() { + void put() { this.redirectAttributes.put("testBean", new TestBean("Fred")); assertThat(this.redirectAttributes.get("testBean")).isEqualTo("Fred"); } @Test - public void putAll() { + void putAll() { Map map = new HashMap<>(); map.put("person", new TestBean("Fred")); map.put("age", 33); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java index d8f92d4de72e..24a9942e3499 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -50,10 +50,10 @@ * @author Alef Arendsen * @author Mark Fisher */ -public class BindTagTests extends AbstractTagTests { +class BindTagTests extends AbstractTagTests { @Test - public void bindTagWithoutErrors() throws JspException { + void bindTagWithoutErrors() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); @@ -76,7 +76,7 @@ public void bindTagWithoutErrors() throws JspException { } @Test - public void bindTagWithGlobalErrors() throws JspException { + void bindTagWithGlobalErrors() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); errors.reject("code1", "message1"); @@ -116,7 +116,7 @@ public void bindTagWithGlobalErrors() throws JspException { } @Test - public void bindTagWithGlobalErrorsAndNoDefaultMessage() throws JspException { + void bindTagWithGlobalErrorsAndNoDefaultMessage() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); errors.reject("code1"); @@ -150,7 +150,7 @@ public void bindTagWithGlobalErrorsAndNoDefaultMessage() throws JspException { } @Test - public void bindTagWithGlobalErrorsAndDefaultMessageOnly() throws JspException { + void bindTagWithGlobalErrorsAndDefaultMessageOnly() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); errors.reject(null, "message1"); @@ -186,7 +186,7 @@ public void bindTagWithGlobalErrorsAndDefaultMessageOnly() throws JspException { } @Test - public void bindStatusGetErrorMessagesAsString() throws JspException { + void bindStatusGetErrorMessagesAsString() throws JspException { // one error (should not include delimiter) PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); @@ -225,7 +225,7 @@ public void bindStatusGetErrorMessagesAsString() throws JspException { } @Test - public void bindTagWithFieldErrors() throws JspException { + void bindTagWithFieldErrors() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); tb.setName("name1"); @@ -263,7 +263,7 @@ public void bindTagWithFieldErrors() throws JspException { status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertThat(status != null).as("Has status variable").isTrue(); assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); - assertThat(new Integer(0).equals(status.getValue())).as("Correct value").isTrue(); + assertThat(Integer.valueOf(0).equals(status.getValue())).as("Correct value").isTrue(); assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); assertThat(status.isError()).as("Correct isError").isTrue(); assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); @@ -295,7 +295,7 @@ public void bindTagWithFieldErrors() throws JspException { } @Test - public void bindTagWithFieldErrorsAndNoDefaultMessage() throws JspException { + void bindTagWithFieldErrorsAndNoDefaultMessage() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); tb.setName("name1"); @@ -328,7 +328,7 @@ public void bindTagWithFieldErrorsAndNoDefaultMessage() throws JspException { status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertThat(status != null).as("Has status variable").isTrue(); assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); - assertThat(new Integer(0).equals(status.getValue())).as("Correct value").isTrue(); + assertThat(Integer.valueOf(0).equals(status.getValue())).as("Correct value").isTrue(); assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); assertThat(status.isError()).as("Correct isError").isTrue(); assertThat(status.getErrorCodes().length == 1).as("Correct errorCodes").isTrue(); @@ -352,7 +352,7 @@ public void bindTagWithFieldErrorsAndNoDefaultMessage() throws JspException { } @Test - public void bindTagWithFieldErrorsAndDefaultMessageOnly() throws JspException { + void bindTagWithFieldErrorsAndDefaultMessageOnly() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); tb.setName("name1"); @@ -386,7 +386,7 @@ public void bindTagWithFieldErrorsAndDefaultMessageOnly() throws JspException { status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE); assertThat(status != null).as("Has status variable").isTrue(); assertThat("age".equals(status.getExpression())).as("Correct expression").isTrue(); - assertThat(new Integer(0).equals(status.getValue())).as("Correct value").isTrue(); + assertThat(Integer.valueOf(0).equals(status.getValue())).as("Correct value").isTrue(); assertThat("0".equals(status.getDisplayValue())).as("Correct displayValue").isTrue(); assertThat(status.isError()).as("Correct isError").isTrue(); assertThat(status.getErrorMessages().length == 1).as("Correct errorMessages").isTrue(); @@ -411,7 +411,7 @@ public void bindTagWithFieldErrorsAndDefaultMessageOnly() throws JspException { } @Test - public void bindTagWithNestedFieldErrors() throws JspException { + void bindTagWithNestedFieldErrors() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); tb.setName("name1"); @@ -439,7 +439,7 @@ public void bindTagWithNestedFieldErrors() throws JspException { } @Test - public void propertyExposing() throws JspException { + void propertyExposing() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); tb.setName("name1"); @@ -464,7 +464,7 @@ public void propertyExposing() throws JspException { } @Test - public void bindTagWithIndexedProperties() throws JspException { + void bindTagWithIndexedProperties() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); @@ -492,7 +492,7 @@ public void bindTagWithIndexedProperties() throws JspException { } @Test - public void bindTagWithMappedProperties() throws JspException { + void bindTagWithMappedProperties() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult(); @@ -520,7 +520,7 @@ public void bindTagWithMappedProperties() throws JspException { } @Test - public void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException { + void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException { PageContext pc = createPageContext(); IndexedTestBean tb = new IndexedTestBean(); DataBinder binder = new ServletRequestDataBinder(tb, "tb"); @@ -549,7 +549,7 @@ public String getAsText() { } @Test - public void bindTagWithToStringAndHtmlEscaping() throws JspException { + void bindTagWithToStringAndHtmlEscaping() throws JspException { PageContext pc = createPageContext(); BindTag tag = new BindTag(); tag.setPageContext(pc); @@ -568,7 +568,7 @@ public void bindTagWithToStringAndHtmlEscaping() throws JspException { } @Test - public void bindTagWithSetValueAndHtmlEscaping() throws JspException { + void bindTagWithSetValueAndHtmlEscaping() throws JspException { PageContext pc = createPageContext(); BindTag tag = new BindTag(); tag.setPageContext(pc); @@ -583,7 +583,7 @@ public void bindTagWithSetValueAndHtmlEscaping() throws JspException { } @Test - public void bindTagWithFieldButWithoutErrorsInstance() throws JspException { + void bindTagWithFieldButWithoutErrorsInstance() throws JspException { PageContext pc = createPageContext(); BindTag tag = new BindTag(); tag.setPageContext(pc); @@ -596,7 +596,7 @@ public void bindTagWithFieldButWithoutErrorsInstance() throws JspException { } @Test - public void bindTagWithFieldButWithoutErrorsInstanceAndHtmlEscaping() throws JspException { + void bindTagWithFieldButWithoutErrorsInstanceAndHtmlEscaping() throws JspException { PageContext pc = createPageContext(); BindTag tag = new BindTag(); tag.setPageContext(pc); @@ -610,7 +610,7 @@ public void bindTagWithFieldButWithoutErrorsInstanceAndHtmlEscaping() throws Jsp } @Test - public void bindTagWithBeanButWithoutErrorsInstance() throws JspException { + void bindTagWithBeanButWithoutErrorsInstance() throws JspException { PageContext pc = createPageContext(); BindTag tag = new BindTag(); tag.setPageContext(pc); @@ -623,7 +623,7 @@ public void bindTagWithBeanButWithoutErrorsInstance() throws JspException { } @Test - public void bindTagWithoutBean() throws JspException { + void bindTagWithoutBean() throws JspException { PageContext pc = createPageContext(); BindTag tag = new BindTag(); tag.setPageContext(pc); @@ -634,7 +634,7 @@ public void bindTagWithoutBean() throws JspException { @Test - public void bindErrorsTagWithoutErrors() throws JspException { + void bindErrorsTagWithoutErrors() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); @@ -646,7 +646,7 @@ public void bindErrorsTagWithoutErrors() throws JspException { } @Test - public void bindErrorsTagWithErrors() throws JspException { + void bindErrorsTagWithErrors() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); errors.reject("test", null, "test"); @@ -659,7 +659,7 @@ public void bindErrorsTagWithErrors() throws JspException { } @Test - public void bindErrorsTagWithoutBean() throws JspException { + void bindErrorsTagWithoutBean() throws JspException { PageContext pc = createPageContext(); BindErrorsTag tag = new BindErrorsTag(); tag.setPageContext(pc); @@ -669,7 +669,7 @@ public void bindErrorsTagWithoutBean() throws JspException { @Test - public void nestedPathDoEndTag() throws JspException { + void nestedPathDoEndTag() throws JspException { PageContext pc = createPageContext(); NestedPathTag tag = new NestedPathTag(); tag.setPath("foo"); @@ -681,7 +681,7 @@ public void nestedPathDoEndTag() throws JspException { } @Test - public void nestedPathDoEndTagWithNesting() throws JspException { + void nestedPathDoEndTagWithNesting() throws JspException { PageContext pc = createPageContext(); NestedPathTag tag = new NestedPathTag(); tag.setPath("foo"); @@ -701,7 +701,7 @@ public void nestedPathDoEndTagWithNesting() throws JspException { } @Test - public void nestedPathDoStartTagInternal() throws JspException { + void nestedPathDoStartTagInternal() throws JspException { PageContext pc = createPageContext(); NestedPathTag tag = new NestedPathTag(); tag.setPath("foo"); @@ -713,7 +713,7 @@ public void nestedPathDoStartTagInternal() throws JspException { } @Test - public void nestedPathDoStartTagInternalWithNesting() throws JspException { + void nestedPathDoStartTagInternalWithNesting() throws JspException { PageContext pc = createPageContext(); NestedPathTag tag = new NestedPathTag(); tag.setPath("foo"); @@ -746,7 +746,7 @@ public void nestedPathDoStartTagInternalWithNesting() throws JspException { } @Test - public void nestedPathWithBindTag() throws JspException { + void nestedPathWithBindTag() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult(); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors); @@ -788,7 +788,7 @@ public void nestedPathWithBindTag() throws JspException { } @Test - public void nestedPathWithBindTagWithIgnoreNestedPath() throws JspException { + void nestedPathWithBindTagWithIgnoreNestedPath() throws JspException { PageContext pc = createPageContext(); Errors errors = new ServletRequestDataBinder(new TestBean(), "tb2").getBindingResult(); pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb2", errors); @@ -810,7 +810,7 @@ public void nestedPathWithBindTagWithIgnoreNestedPath() throws JspException { } @Test - public void transformTagCorrectBehavior() throws JspException { + void transformTagCorrectBehavior() throws JspException { // first set up the pagecontext and the bean PageContext pc = createPageContext(); TestBean tb = new TestBean(); @@ -855,7 +855,7 @@ public void transformTagCorrectBehavior() throws JspException { } @Test - public void transformTagWithHtmlEscape() throws JspException { + void transformTagWithHtmlEscape() throws JspException { // first set up the PageContext and the bean PageContext pc = createPageContext(); TestBean tb = new TestBean(); @@ -884,7 +884,7 @@ public void transformTagWithHtmlEscape() throws JspException { } @Test - public void transformTagOutsideBindTag() throws JspException { + void transformTagOutsideBindTag() throws JspException { // first set up the pagecontext and the bean PageContext pc = createPageContext(); TestBean tb = new TestBean(); @@ -915,7 +915,7 @@ public void transformTagOutsideBindTag() throws JspException { } @Test - public void transformTagNonExistingValue() throws JspException { + void transformTagNonExistingValue() throws JspException { // first set up the pagecontext and the bean PageContext pc = createPageContext(); TestBean tb = new TestBean(); @@ -942,7 +942,7 @@ public void transformTagNonExistingValue() throws JspException { } @Test - public void transformTagWithSettingOfScope() throws JspException { + void transformTagWithSettingOfScope() throws JspException { // first set up the pagecontext and the bean PageContext pc = createPageContext(); TestBean tb = new TestBean(); @@ -997,7 +997,7 @@ public void transformTagWithSettingOfScope() throws JspException { */ @SuppressWarnings("serial") @Test - public void nestingInFormTag() throws JspException { + void nestingInFormTag() throws JspException { PageContext pc = createPageContext(); TestBean tb = new TestBean(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java index 164a41582682..39e1bb710b9a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 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. @@ -49,7 +49,7 @@ * @author Jeremy Grelle */ @SuppressWarnings({ "rawtypes", "unchecked" }) -public class CheckboxTagTests extends AbstractFormTagTests { +class CheckboxTagTests extends AbstractFormTagTests { private CheckboxTag tag; @@ -68,7 +68,7 @@ protected TagWriter createTagWriter() { } @Test - public void withSingleValueBooleanObjectChecked() throws Exception { + void withSingleValueBooleanObjectChecked() throws Exception { this.tag.setPath("someBoolean"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); @@ -91,7 +91,7 @@ public void withSingleValueBooleanObjectChecked() throws Exception { } @Test - public void withIndexedBooleanObjectNotChecked() throws Exception { + void withIndexedBooleanObjectNotChecked() throws Exception { this.tag.setPath("someMap[key]"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); @@ -114,7 +114,7 @@ public void withIndexedBooleanObjectNotChecked() throws Exception { } @Test - public void withSingleValueBooleanObjectCheckedAndDynamicAttributes() throws Exception { + void withSingleValueBooleanObjectCheckedAndDynamicAttributes() throws Exception { String dynamicAttribute1 = "attr1"; String dynamicAttribute2 = "attr2"; @@ -144,7 +144,7 @@ public void withSingleValueBooleanObjectCheckedAndDynamicAttributes() throws Exc } @Test - public void withSingleValueBooleanChecked() throws Exception { + void withSingleValueBooleanChecked() throws Exception { this.tag.setPath("jedi"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); @@ -164,7 +164,7 @@ public void withSingleValueBooleanChecked() throws Exception { } @Test - public void withSingleValueBooleanObjectUnchecked() throws Exception { + void withSingleValueBooleanObjectUnchecked() throws Exception { this.bean.setSomeBoolean(Boolean.FALSE); this.tag.setPath("someBoolean"); int result = this.tag.doStartTag(); @@ -186,7 +186,7 @@ public void withSingleValueBooleanObjectUnchecked() throws Exception { } @Test - public void withSingleValueBooleanUnchecked() throws Exception { + void withSingleValueBooleanUnchecked() throws Exception { this.bean.setJedi(false); this.tag.setPath("jedi"); int result = this.tag.doStartTag(); @@ -208,7 +208,7 @@ public void withSingleValueBooleanUnchecked() throws Exception { } @Test - public void withSingleValueNull() throws Exception { + void withSingleValueNull() throws Exception { this.bean.setName(null); this.tag.setPath("name"); this.tag.setValue("Rob Harrop"); @@ -231,7 +231,7 @@ public void withSingleValueNull() throws Exception { } @Test - public void withSingleValueNotNull() throws Exception { + void withSingleValueNotNull() throws Exception { this.bean.setName("Rob Harrop"); this.tag.setPath("name"); this.tag.setValue("Rob Harrop"); @@ -254,7 +254,7 @@ public void withSingleValueNotNull() throws Exception { } @Test - public void withSingleValueAndEditor() throws Exception { + void withSingleValueAndEditor() throws Exception { this.bean.setName("Rob Harrop"); this.tag.setPath("name"); this.tag.setValue(" Rob Harrop"); @@ -281,7 +281,7 @@ public void withSingleValueAndEditor() throws Exception { } @Test - public void withMultiValueChecked() throws Exception { + void withMultiValueChecked() throws Exception { this.tag.setPath("stringArray"); this.tag.setValue("foo"); int result = this.tag.doStartTag(); @@ -303,7 +303,7 @@ public void withMultiValueChecked() throws Exception { } @Test - public void withMultiValueUnchecked() throws Exception { + void withMultiValueUnchecked() throws Exception { this.tag.setPath("stringArray"); this.tag.setValue("abc"); int result = this.tag.doStartTag(); @@ -325,7 +325,7 @@ public void withMultiValueUnchecked() throws Exception { } @Test - public void withMultiValueWithEditor() throws Exception { + void withMultiValueWithEditor() throws Exception { this.tag.setPath("stringArray"); this.tag.setValue(" foo"); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); @@ -353,7 +353,7 @@ public void withMultiValueWithEditor() throws Exception { } @Test - public void withMultiValueIntegerWithEditor() throws Exception { + void withMultiValueIntegerWithEditor() throws Exception { this.tag.setPath("someIntegerArray"); this.tag.setValue(" 1"); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); @@ -381,7 +381,7 @@ public void withMultiValueIntegerWithEditor() throws Exception { } @Test - public void withCollection() throws Exception { + void withCollection() throws Exception { this.tag.setPath("someList"); this.tag.setValue("foo"); int result = this.tag.doStartTag(); @@ -403,7 +403,7 @@ public void withCollection() throws Exception { } @Test - public void withObjectChecked() throws Exception { + void withObjectChecked() throws Exception { this.tag.setPath("date"); this.tag.setValue(getDate()); @@ -426,7 +426,7 @@ public void withObjectChecked() throws Exception { } @Test - public void withObjectUnchecked() throws Exception { + void withObjectUnchecked() throws Exception { this.tag.setPath("date"); Date date = new Date(); this.tag.setValue(date); @@ -450,7 +450,7 @@ public void withObjectUnchecked() throws Exception { } @Test - public void collectionOfColoursSelected() throws Exception { + void collectionOfColoursSelected() throws Exception { this.tag.setPath("otherColours"); this.tag.setValue("RED"); @@ -472,7 +472,7 @@ public void collectionOfColoursSelected() throws Exception { } @Test - public void collectionOfColoursNotSelected() throws Exception { + void collectionOfColoursNotSelected() throws Exception { this.tag.setPath("otherColours"); this.tag.setValue("PURPLE"); @@ -494,7 +494,7 @@ public void collectionOfColoursNotSelected() throws Exception { } @Test - public void collectionOfPetsAsString() throws Exception { + void collectionOfPetsAsString() throws Exception { this.tag.setPath("pets"); this.tag.setValue("Spot"); @@ -516,7 +516,7 @@ public void collectionOfPetsAsString() throws Exception { } @Test - public void collectionOfPetsAsStringNotSelected() throws Exception { + void collectionOfPetsAsStringNotSelected() throws Exception { this.tag.setPath("pets"); this.tag.setValue("Santa's Little Helper"); @@ -538,7 +538,7 @@ public void collectionOfPetsAsStringNotSelected() throws Exception { } @Test - public void collectionOfPets() throws Exception { + void collectionOfPets() throws Exception { this.tag.setPath("pets"); this.tag.setValue(new Pet("Rudiger")); @@ -561,7 +561,7 @@ public void collectionOfPets() throws Exception { } @Test - public void collectionOfPetsNotSelected() throws Exception { + void collectionOfPetsNotSelected() throws Exception { this.tag.setPath("pets"); this.tag.setValue(new Pet("Santa's Little Helper")); @@ -584,7 +584,7 @@ public void collectionOfPetsNotSelected() throws Exception { } @Test - public void collectionOfPetsWithEditor() throws Exception { + void collectionOfPetsWithEditor() throws Exception { this.tag.setPath("pets"); this.tag.setValue(new ItemPet("Rudiger")); @@ -612,14 +612,14 @@ public void collectionOfPetsWithEditor() throws Exception { } @Test - public void withNullValue() throws Exception { + void withNullValue() throws Exception { this.tag.setPath("name"); assertThatIllegalArgumentException().as("null value binding to a non-boolean").isThrownBy( this.tag::doStartTag); } @Test - public void hiddenElementOmittedOnDisabled() throws Exception { + void hiddenElementOmittedOnDisabled() throws Exception { this.tag.setPath("someBoolean"); this.tag.setDisabled(true); int result = this.tag.doStartTag(); @@ -642,7 +642,7 @@ public void hiddenElementOmittedOnDisabled() throws Exception { } @Test - public void dynamicTypeAttribute() throws JspException { + void dynamicTypeAttribute() throws JspException { assertThatIllegalArgumentException().isThrownBy(() -> this.tag.setDynamicAttribute(null, "type", "email")) .withMessage("Attribute type=\"email\" is not allowed"); @@ -718,7 +718,7 @@ private class MyIntegerEditor extends PropertyEditorSupport { @Override public void setAsText(String text) { this.count++; - setValue(new Integer(text.trim())); + setValue(Integer.valueOf(text.trim())); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java index 29c95bda5590..e323aff62bba 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -30,7 +30,7 @@ /** * @author Rob Harrop */ -public class HiddenInputTagTests extends AbstractFormTagTests { +class HiddenInputTagTests extends AbstractFormTagTests { private HiddenInputTag tag; @@ -49,7 +49,7 @@ protected TagWriter createTagWriter() { } @Test - public void render() throws Exception { + void render() throws Exception { this.tag.setPath("name"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(Tag.SKIP_BODY); @@ -65,7 +65,7 @@ public void render() throws Exception { } @Test - public void withCustomBinder() throws Exception { + void withCustomBinder() throws Exception { this.tag.setPath("myFloat"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); @@ -84,14 +84,14 @@ public void withCustomBinder() throws Exception { } @Test - public void dynamicTypeAttribute() throws JspException { + void dynamicTypeAttribute() throws JspException { assertThatIllegalArgumentException().isThrownBy(() -> this.tag.setDynamicAttribute(null, "type", "email")) .withMessage("Attribute type=\"email\" is not allowed"); } @Test - public void disabledTrue() throws Exception { + void disabledTrue() throws Exception { this.tag.setDisabled(true); this.tag.doStartTag(); @@ -107,7 +107,7 @@ public void disabledTrue() throws Exception { // SPR-8661 @Test - public void disabledFalse() throws Exception { + void disabledFalse() throws Exception { this.tag.setDisabled(false); this.tag.doStartTag(); @@ -132,7 +132,7 @@ private void assertTagOpened(String output) { protected TestBean createTestBean() { this.bean = new TestBean(); bean.setName("Sally Greenwood"); - bean.setMyFloat(new Float("12.34")); + bean.setMyFloat(Float.valueOf("12.34")); return bean; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java index a68de172d710..59def204ee51 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java @@ -56,7 +56,7 @@ protected TestBean createTestBean() { // set up test data this.rob = new TestBean(); this.rob.setName("Rob"); - this.rob.setMyFloat(new Float(12.34)); + this.rob.setMyFloat(Float.valueOf(12.34f)); TestBean sally = new TestBean(); sally.setName("Sally"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java index 54de88290b91..a94bee41a7d7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 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. @@ -46,7 +46,7 @@ * @author Jeremy Grelle */ @SuppressWarnings({ "rawtypes", "unchecked" }) -public class OptionTagTests extends AbstractHtmlElementTagTests { +class OptionTagTests extends AbstractHtmlElementTagTests { private static final String ARRAY_SOURCE = "abc,123,def"; @@ -79,7 +79,7 @@ public String getName() { @Test - public void canBeDisabledEvenWhenSelected() throws Exception { + void canBeDisabledEvenWhenSelected() throws Exception { String selectName = "testBean.name"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); @@ -101,7 +101,7 @@ public void canBeDisabledEvenWhenSelected() throws Exception { } @Test - public void renderNotSelected() throws Exception { + void renderNotSelected() throws Exception { String selectName = "testBean.name"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); @@ -121,7 +121,7 @@ public void renderNotSelected() throws Exception { } @Test - public void renderWithDynamicAttributes() throws Exception { + void renderWithDynamicAttributes() throws Exception { String dynamicAttribute1 = "attr1"; String dynamicAttribute2 = "attr2"; @@ -149,7 +149,7 @@ public void renderWithDynamicAttributes() throws Exception { } @Test - public void renderSelected() throws Exception { + void renderSelected() throws Exception { String selectName = "testBean.name"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); @@ -172,7 +172,7 @@ public void renderSelected() throws Exception { } @Test - public void withNoLabel() throws Exception { + void withNoLabel() throws Exception { String selectName = "testBean.name"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); @@ -195,7 +195,7 @@ public void withNoLabel() throws Exception { } @Test - public void withoutContext() throws Exception { + void withoutContext() throws Exception { this.tag.setParent(null); this.tag.setValue("foo"); this.tag.setLabel("Foo"); @@ -204,7 +204,7 @@ public void withoutContext() throws Exception { } @Test - public void withPropertyEditor() throws Exception { + void withPropertyEditor() throws Exception { String selectName = "testBean.stringArray"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) { @Override @@ -233,7 +233,7 @@ public PropertyEditor getEditor() { } @Test - public void withPropertyEditorStringComparison() throws Exception { + void withPropertyEditorStringComparison() throws Exception { final PropertyEditor testBeanEditor = new TestBeanPropertyEditor(); testBeanEditor.setValue(new TestBean("Sally")); String selectName = "testBean.spouse"; @@ -261,11 +261,11 @@ public PropertyEditor getEditor() { } @Test - public void withCustomObjectSelected() throws Exception { + void withCustomObjectSelected() throws Exception { String selectName = "testBean.someNumber"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); - this.tag.setValue(new Float(12.34)); + this.tag.setValue(12.34f); this.tag.setLabel("GBP 12.34"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(BodyTag.EVAL_BODY_BUFFERED); @@ -282,11 +282,11 @@ public void withCustomObjectSelected() throws Exception { } @Test - public void withCustomObjectNotSelected() throws Exception { + void withCustomObjectNotSelected() throws Exception { String selectName = "testBean.someNumber"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); - this.tag.setValue(new Float(12.35)); + this.tag.setValue(12.35f); this.tag.setLabel("GBP 12.35"); int result = this.tag.doStartTag(); assertThat(result).isEqualTo(BodyTag.EVAL_BODY_BUFFERED); @@ -303,9 +303,9 @@ public void withCustomObjectNotSelected() throws Exception { } @Test - public void withCustomObjectAndEditorSelected() throws Exception { + void withCustomObjectAndEditorSelected() throws Exception { final PropertyEditor floatEditor = new SimpleFloatEditor(); - floatEditor.setValue(new Float("12.34")); + floatEditor.setValue(Float.valueOf("12.34")); String selectName = "testBean.someNumber"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) { @Override @@ -315,7 +315,7 @@ public PropertyEditor getEditor() { }; getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); - this.tag.setValue(new Float(12.34)); + this.tag.setValue(12.34f); this.tag.setLabel("12.34f"); int result = this.tag.doStartTag(); @@ -331,7 +331,7 @@ public PropertyEditor getEditor() { } @Test - public void withCustomObjectAndEditorNotSelected() throws Exception { + void withCustomObjectAndEditorNotSelected() throws Exception { final PropertyEditor floatEditor = new SimpleFloatEditor(); String selectName = "testBean.someNumber"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) { @@ -342,7 +342,7 @@ public PropertyEditor getEditor() { }; getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); - this.tag.setValue(new Float(12.35)); + this.tag.setValue(12.35f); this.tag.setLabel("12.35f"); int result = this.tag.doStartTag(); @@ -358,7 +358,7 @@ public PropertyEditor getEditor() { } @Test - public void asBodyTag() throws Exception { + void asBodyTag() throws Exception { String selectName = "testBean.name"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); @@ -380,7 +380,7 @@ public void asBodyTag() throws Exception { } @Test - public void asBodyTagSelected() throws Exception { + void asBodyTagSelected() throws Exception { String selectName = "testBean.name"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); @@ -401,7 +401,7 @@ public void asBodyTagSelected() throws Exception { } @Test - public void asBodyTagCollapsed() throws Exception { + void asBodyTagCollapsed() throws Exception { String selectName = "testBean.name"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false); getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus); @@ -423,7 +423,7 @@ public void asBodyTagCollapsed() throws Exception { } @Test - public void asBodyTagWithEditor() throws Exception { + void asBodyTagWithEditor() throws Exception { String selectName = "testBean.stringArray"; BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) { @Override @@ -447,7 +447,7 @@ public PropertyEditor getEditor() { } @Test - public void multiBind() throws Exception { + void multiBind() throws Exception { BeanPropertyBindingResult result = new BeanPropertyBindingResult(new TestBean(), "testBean"); result.getPropertyAccessor().registerCustomEditor(TestBean.class, "friends", new FriendEditor()); exposeBindingResult(result); @@ -463,7 +463,7 @@ public void multiBind() throws Exception { } @Test - public void optionTagNotNestedWithinSelectTag() throws Exception { + void optionTagNotNestedWithinSelectTag() throws Exception { tag.setParent(null); tag.setValue("foo"); assertThatIllegalStateException().as("when not nested within a