Browse Source

Minor improvements in spring-test

- Remove final modifier from private method
- Use StandardCharsets
- Remove unnecessary toString calls
- Remove unnecessary static modifiers
- Refactor to use enhanced switch
- Replace concatenated strings with text blocks
- Rely on auto-boxing where appropriate
- Remove unnecessary code
- Fix imports in Kotlin test classes

Closes gh-29413
pull/27328/merge
Kulwant Singh 2 years ago committed by Sam Brannen
parent
commit
debe78b7f9
  1. 2
      spring-test/src/main/java/org/springframework/test/context/junit/jupiter/AbstractExpressionEvaluatingCondition.java
  2. 2
      spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericContextLoader.java
  3. 2
      spring-test/src/main/java/org/springframework/test/context/testng/AbstractTestNGSpringContextTests.java
  4. 2
      spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java
  5. 2
      spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/BootstrapWithTestInterface.java
  6. 2
      spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextConfigurationTestInterface.java
  7. 2
      spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/WebAppConfigurationTestInterface.java
  8. 8
      spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig.java
  9. 4
      spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfig.java
  10. 23
      spring-test/src/test/java/org/springframework/test/context/junit4/rules/ProgrammaticTxMgmtSpringRuleTests.java
  11. 2
      spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AnnotatedConfigClassesWithoutAtConfigurationTests.java
  12. 2
      spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java
  13. 23
      spring-test/src/test/java/org/springframework/test/context/testng/transaction/programmatic/ProgrammaticTxMgmtTestNGTests.java
  14. 23
      spring-test/src/test/java/org/springframework/test/context/transaction/programmatic/ProgrammaticTxMgmtTests.java
  15. 50
      spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java
  16. 8
      spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java
  17. 47
      spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java
  18. 30
      spring-test/src/test/java/org/springframework/test/web/client/UnorderedRequestExpectationManagerTests.java
  19. 7
      spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/SoftAssertionTests.java
  20. 3
      spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/DelegatingWebConnectionTests.java
  21. 2
      spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java
  22. 6
      spring-test/src/test/java/org/springframework/test/web/servlet/result/ContentResultMatchersTests.java
  23. 4
      spring-test/src/test/java/org/springframework/test/web/servlet/result/JsonPathResultMatchersTests.java
  24. 9
      spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java
  25. 23
      spring-test/src/test/java/org/springframework/test/web/servlet/result/StatusResultMatchersTests.java
  26. 13
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/ExceptionHandlerTests.java
  27. 11
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/XpathAssertionTests.java
  28. 13
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ExceptionHandlerTests.java
  29. 18
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/MultipartControllerTests.java
  30. 2
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerSmokeTests.java
  31. 8
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java
  32. 11
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/XpathAssertionTests.java
  33. 18
      spring-test/src/test/kotlin/org/springframework/test/web/servlet/MockMvcExtensionsTests.kt

2
spring-test/src/main/java/org/springframework/test/context/junit/jupiter/AbstractExpressionEvaluatingCondition.java

@ -93,7 +93,7 @@ abstract class AbstractExpressionEvaluatingCondition implements ExecutionConditi
AnnotatedElement element = context.getElement().get(); AnnotatedElement element = context.getElement().get();
Optional<A> annotation = findMergedAnnotation(element, annotationType); Optional<A> annotation = findMergedAnnotation(element, annotationType);
if (!annotation.isPresent()) { if (annotation.isEmpty()) {
String reason = String.format("%s is enabled since @%s is not present", element, String reason = String.format("%s is enabled since @%s is not present", element,
annotationType.getSimpleName()); annotationType.getSimpleName());
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {

2
spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericContextLoader.java

@ -188,7 +188,7 @@ public abstract class AbstractGenericContextLoader extends AbstractContextLoader
* register a JVM shutdown hook for it * register a JVM shutdown hook for it
* @return a new application context * @return a new application context
*/ */
private final GenericApplicationContext loadContext( private GenericApplicationContext loadContext(
MergedContextConfiguration mergedConfig, boolean forAotProcessing) throws Exception { MergedContextConfiguration mergedConfig, boolean forAotProcessing) throws Exception {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {

2
spring-test/src/main/java/org/springframework/test/context/testng/AbstractTestNGSpringContextTests.java

@ -201,7 +201,7 @@ public abstract class AbstractTestNGSpringContextTests implements IHookable, App
private Throwable getTestResultException(ITestResult testResult) { private Throwable getTestResultException(ITestResult testResult) {
Throwable testResultException = testResult.getThrowable(); Throwable testResultException = testResult.getThrowable();
if (testResultException instanceof InvocationTargetException) { if (testResultException instanceof InvocationTargetException) {
testResultException = ((InvocationTargetException) testResultException).getCause(); testResultException = testResultException.getCause();
} }
return testResultException; return testResultException;
} }

2
spring-test/src/main/java/org/springframework/test/util/XmlExpectationsHelper.java

@ -82,7 +82,7 @@ public class XmlExpectationsHelper {
public void assertXmlEqual(String expected, String actual) throws Exception { public void assertXmlEqual(String expected, String actual) throws Exception {
XmlUnitDiff diff = new XmlUnitDiff(expected, actual); XmlUnitDiff diff = new XmlUnitDiff(expected, actual);
if (diff.hasDifferences()) { if (diff.hasDifferences()) {
AssertionErrors.fail("Body content " + diff.toString()); AssertionErrors.fail("Body content " + diff);
} }
} }

2
spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/BootstrapWithTestInterface.java

@ -34,7 +34,7 @@ import static java.util.Collections.singletonList;
@BootstrapWith(CustomTestContextBootstrapper.class) @BootstrapWith(CustomTestContextBootstrapper.class)
interface BootstrapWithTestInterface { interface BootstrapWithTestInterface {
static class CustomTestContextBootstrapper extends DefaultTestContextBootstrapper { class CustomTestContextBootstrapper extends DefaultTestContextBootstrapper {
@Override @Override
protected List<ContextCustomizerFactory> getContextCustomizerFactories() { protected List<ContextCustomizerFactory> getContextCustomizerFactories() {

2
spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ContextConfigurationTestInterface.java

@ -28,7 +28,7 @@ import org.springframework.test.context.configuration.interfaces.ContextConfigur
@ContextConfiguration(classes = Config.class) @ContextConfiguration(classes = Config.class)
interface ContextConfigurationTestInterface { interface ContextConfigurationTestInterface {
static class Config { class Config {
@Bean @Bean
Employee employee() { Employee employee() {

2
spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/WebAppConfigurationTestInterface.java

@ -30,7 +30,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
interface WebAppConfigurationTestInterface { interface WebAppConfigurationTestInterface {
@Configuration @Configuration
static class Config { class Config {
/* no user beans required for these tests */ /* no user beans required for these tests */
} }

8
spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig.java

@ -52,7 +52,7 @@ public @interface ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig {
@Configuration @Configuration
@Profile("dev") @Profile("dev")
static class DevConfig { class DevConfig {
@Bean @Bean
public String foo() { public String foo() {
@ -62,7 +62,7 @@ public @interface ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig {
@Configuration @Configuration
@Profile("prod") @Profile("prod")
static class ProductionConfig { class ProductionConfig {
@Bean @Bean
public String foo() { public String foo() {
@ -72,7 +72,7 @@ public @interface ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig {
@Configuration @Configuration
@Profile("resolver") @Profile("resolver")
static class ResolverConfig { class ResolverConfig {
@Bean @Bean
public String foo() { public String foo() {
@ -80,7 +80,7 @@ public @interface ConfigClassesAndProfileResolverWithCustomDefaultsMetaConfig {
} }
} }
static class CustomResolver implements ActiveProfilesResolver { class CustomResolver implements ActiveProfilesResolver {
@Override @Override
public String[] resolve(Class<?> testClass) { public String[] resolve(Class<?> testClass) {

4
spring-test/src/test/java/org/springframework/test/context/junit4/annotation/meta/ConfigClassesAndProfilesWithCustomDefaultsMetaConfig.java

@ -50,7 +50,7 @@ public @interface ConfigClassesAndProfilesWithCustomDefaultsMetaConfig {
@Configuration @Configuration
@Profile("dev") @Profile("dev")
static class DevConfig { class DevConfig {
@Bean @Bean
public String foo() { public String foo() {
@ -60,7 +60,7 @@ public @interface ConfigClassesAndProfilesWithCustomDefaultsMetaConfig {
@Configuration @Configuration
@Profile("prod") @Profile("prod")
static class ProductionConfig { class ProductionConfig {
@Bean @Bean
public String foo() { public String foo() {

23
spring-test/src/test/java/org/springframework/test/context/junit4/rules/ProgrammaticTxMgmtSpringRuleTests.java

@ -97,24 +97,11 @@ public class ProgrammaticTxMgmtSpringRuleTests {
void afterTransaction() { void afterTransaction() {
String method = this.testName.getMethodName(); String method = this.testName.getMethodName();
switch (method) { switch (method) {
case "commitTxAndStartNewTx": case "commitTxAndStartNewTx", "commitTxButDoNotStartNewTx" -> assertUsers("Dogbert");
case "commitTxButDoNotStartNewTx": { case "rollbackTxAndStartNewTx", "rollbackTxButDoNotStartNewTx", "startTxWithExistingTransaction" ->
assertUsers("Dogbert"); assertUsers("Dilbert");
break; case "rollbackTxAndStartNewTxWithDefaultCommitSemantics" -> assertUsers("Dilbert", "Dogbert");
} default -> fail("missing 'after transaction' assertion for test method: " + method);
case "rollbackTxAndStartNewTx":
case "rollbackTxButDoNotStartNewTx":
case "startTxWithExistingTransaction": {
assertUsers("Dilbert");
break;
}
case "rollbackTxAndStartNewTxWithDefaultCommitSemantics": {
assertUsers("Dilbert", "Dogbert");
break;
}
default: {
fail("missing 'after transaction' assertion for test method: " + method);
}
} }
} }

2
spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AnnotatedConfigClassesWithoutAtConfigurationTests.java

@ -94,7 +94,7 @@ public class AnnotatedConfigClassesWithoutAtConfigurationTests {
assertThat(lifecycleBean).isNotNull(); assertThat(lifecycleBean).isNotNull();
assertThat(lifecycleBean.isInitialized()).isTrue(); assertThat(lifecycleBean.isInitialized()).isTrue();
Set<String> names = new HashSet<>(); Set<String> names = new HashSet<>();
names.add(enigma.toString()); names.add(enigma);
names.add(lifecycleBean.getName()); names.add(lifecycleBean.getName());
assertThat(new HashSet<>(Arrays.asList("enigma #1", "enigma #2"))).isEqualTo(names); assertThat(new HashSet<>(Arrays.asList("enigma #1", "enigma #2"))).isEqualTo(names);
} }

2
spring-test/src/test/java/org/springframework/test/context/support/DelegatingSmartContextLoaderTests.java

@ -219,7 +219,7 @@ class DelegatingSmartContextLoaderTests {
@Bean @Bean
public String foo() { public String foo() {
return new String("foo"); return "foo";
} }
} }

23
spring-test/src/test/java/org/springframework/test/context/testng/transaction/programmatic/ProgrammaticTxMgmtTestNGTests.java

@ -73,24 +73,11 @@ public class ProgrammaticTxMgmtTestNGTests extends AbstractTransactionalTestNGSp
@AfterTransaction @AfterTransaction
public void afterTransaction() { public void afterTransaction() {
switch (this.methodName) { switch (this.methodName) {
case "commitTxAndStartNewTx": case "commitTxAndStartNewTx", "commitTxButDoNotStartNewTx" -> assertUsers("Dogbert");
case "commitTxButDoNotStartNewTx": { case "rollbackTxAndStartNewTx", "rollbackTxButDoNotStartNewTx", "startTxWithExistingTransaction" ->
assertUsers("Dogbert"); assertUsers("Dilbert");
break; case "rollbackTxAndStartNewTxWithDefaultCommitSemantics" -> assertUsers("Dilbert", "Dogbert");
} default -> fail("missing 'after transaction' assertion for test method: " + this.methodName);
case "rollbackTxAndStartNewTx":
case "rollbackTxButDoNotStartNewTx":
case "startTxWithExistingTransaction": {
assertUsers("Dilbert");
break;
}
case "rollbackTxAndStartNewTxWithDefaultCommitSemantics": {
assertUsers("Dilbert", "Dogbert");
break;
}
default: {
fail("missing 'after transaction' assertion for test method: " + this.methodName);
}
} }
} }

23
spring-test/src/test/java/org/springframework/test/context/transaction/programmatic/ProgrammaticTxMgmtTests.java

@ -88,24 +88,11 @@ class ProgrammaticTxMgmtTests {
@AfterTransaction @AfterTransaction
void afterTransaction() { void afterTransaction() {
switch (this.methodName) { switch (this.methodName) {
case "commitTxAndStartNewTx": case "commitTxAndStartNewTx", "commitTxButDoNotStartNewTx" -> assertUsers("Dogbert");
case "commitTxButDoNotStartNewTx": { case "rollbackTxAndStartNewTx", "rollbackTxButDoNotStartNewTx", "startTxWithExistingTransaction" ->
assertUsers("Dogbert"); assertUsers("Dilbert");
break; case "rollbackTxAndStartNewTxWithDefaultCommitSemantics" -> assertUsers("Dilbert", "Dogbert");
} default -> fail("missing 'after transaction' assertion for test method: " + this.methodName);
case "rollbackTxAndStartNewTx":
case "rollbackTxButDoNotStartNewTx":
case "startTxWithExistingTransaction": {
assertUsers("Dilbert");
break;
}
case "rollbackTxAndStartNewTxWithDefaultCommitSemantics": {
assertUsers("Dilbert", "Dogbert");
break;
}
default: {
fail("missing 'after transaction' assertion for test method: " + this.methodName);
}
} }
} }

50
spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java

@ -46,7 +46,7 @@ import static org.springframework.test.util.ReflectionTestUtils.setField;
*/ */
class ReflectionTestUtilsTests { class ReflectionTestUtilsTests {
private static final Float PI = Float.valueOf((float) 22 / 7); private static final Float PI = (float) 22 / 7;
private final Person person = new PersonEntity(); private final Person person = new PersonEntity();
@ -64,7 +64,7 @@ class ReflectionTestUtilsTests {
@Test @Test
void setFieldWithNullTargetObject() throws Exception { void setFieldWithNullTargetObject() throws Exception {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> setField((Object) null, "id", Long.valueOf(99))) .isThrownBy(() -> setField((Object) null, "id", 99L))
.withMessageStartingWith("Either targetObject or targetClass"); .withMessageStartingWith("Either targetObject or targetClass");
} }
@ -78,7 +78,7 @@ class ReflectionTestUtilsTests {
@Test @Test
void setFieldWithNullTargetClass() throws Exception { void setFieldWithNullTargetClass() throws Exception {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> setField((Class<?>) null, "id", Long.valueOf(99))) .isThrownBy(() -> setField((Class<?>) null, "id", 99L))
.withMessageStartingWith("Either targetObject or targetClass"); .withMessageStartingWith("Either targetObject or targetClass");
} }
@ -92,21 +92,21 @@ class ReflectionTestUtilsTests {
@Test @Test
void setFieldWithNullNameAndNullType() throws Exception { void setFieldWithNullNameAndNullType() throws Exception {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> setField(person, null, Long.valueOf(99), null)) .isThrownBy(() -> setField(person, null, 99L, null))
.withMessageStartingWith("Either name or type"); .withMessageStartingWith("Either name or type");
} }
@Test @Test
void setFieldWithBogusName() throws Exception { void setFieldWithBogusName() throws Exception {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> setField(person, "bogus", Long.valueOf(99), long.class)) .isThrownBy(() -> setField(person, "bogus", 99L, long.class))
.withMessageStartingWith("Could not find field 'bogus'"); .withMessageStartingWith("Could not find field 'bogus'");
} }
@Test @Test
void setFieldWithWrongType() throws Exception { void setFieldWithWrongType() throws Exception {
assertThatIllegalArgumentException() assertThatIllegalArgumentException()
.isThrownBy(() -> setField(person, "id", Long.valueOf(99), String.class)) .isThrownBy(() -> setField(person, "id", 99L, String.class))
.withMessageStartingWith("Could not find field"); .withMessageStartingWith("Could not find field");
} }
@ -135,17 +135,17 @@ class ReflectionTestUtilsTests {
private static void assertSetFieldAndGetFieldBehavior(Person person) { private static void assertSetFieldAndGetFieldBehavior(Person person) {
// Set reflectively // Set reflectively
setField(person, "id", Long.valueOf(99), long.class); setField(person, "id", 99L, long.class);
setField(person, "name", "Tom"); setField(person, "name", "Tom");
setField(person, "age", Integer.valueOf(42)); setField(person, "age", 42);
setField(person, "eyeColor", "blue", String.class); setField(person, "eyeColor", "blue", String.class);
setField(person, "likesPets", Boolean.TRUE); setField(person, "likesPets", Boolean.TRUE);
setField(person, "favoriteNumber", PI, Number.class); setField(person, "favoriteNumber", PI, Number.class);
// Get reflectively // Get reflectively
assertThat(getField(person, "id")).isEqualTo(Long.valueOf(99)); assertThat(getField(person, "id")).isEqualTo(99L);
assertThat(getField(person, "name")).isEqualTo("Tom"); assertThat(getField(person, "name")).isEqualTo("Tom");
assertThat(getField(person, "age")).isEqualTo(Integer.valueOf(42)); assertThat(getField(person, "age")).isEqualTo(42);
assertThat(getField(person, "eyeColor")).isEqualTo("blue"); assertThat(getField(person, "eyeColor")).isEqualTo("blue");
assertThat(getField(person, "likesPets")).isEqualTo(Boolean.TRUE); assertThat(getField(person, "likesPets")).isEqualTo(Boolean.TRUE);
assertThat(getField(person, "favoriteNumber")).isEqualTo(PI); assertThat(getField(person, "favoriteNumber")).isEqualTo(PI);
@ -249,33 +249,33 @@ class ReflectionTestUtilsTests {
@Test @Test
void invokeSetterMethodAndInvokeGetterMethodWithExplicitMethodNames() throws Exception { void invokeSetterMethodAndInvokeGetterMethodWithExplicitMethodNames() throws Exception {
invokeSetterMethod(person, "setId", Long.valueOf(1), long.class); invokeSetterMethod(person, "setId", 1L, long.class);
invokeSetterMethod(person, "setName", "Jerry", String.class); invokeSetterMethod(person, "setName", "Jerry", String.class);
invokeSetterMethod(person, "setAge", Integer.valueOf(33), int.class); invokeSetterMethod(person, "setAge", 33, int.class);
invokeSetterMethod(person, "setEyeColor", "green", String.class); invokeSetterMethod(person, "setEyeColor", "green", String.class);
invokeSetterMethod(person, "setLikesPets", Boolean.FALSE, boolean.class); invokeSetterMethod(person, "setLikesPets", Boolean.FALSE, boolean.class);
invokeSetterMethod(person, "setFavoriteNumber", Integer.valueOf(42), Number.class); invokeSetterMethod(person, "setFavoriteNumber", 42, Number.class);
assertThat(person.getId()).as("ID (protected method in a superclass)").isEqualTo(1); assertThat(person.getId()).as("ID (protected method in a superclass)").isEqualTo(1);
assertThat(person.getName()).as("name (private method)").isEqualTo("Jerry"); assertThat(person.getName()).as("name (private method)").isEqualTo("Jerry");
assertThat(person.getAge()).as("age (protected method)").isEqualTo(33); assertThat(person.getAge()).as("age (protected method)").isEqualTo(33);
assertThat(person.getEyeColor()).as("eye color (package private method)").isEqualTo("green"); assertThat(person.getEyeColor()).as("eye color (package private method)").isEqualTo("green");
assertThat(person.likesPets()).as("'likes pets' flag (protected method for a boolean)").isFalse(); assertThat(person.likesPets()).as("'likes pets' flag (protected method for a boolean)").isFalse();
assertThat(person.getFavoriteNumber()).as("'favorite number' (protected method for a Number)").isEqualTo(Integer.valueOf(42)); assertThat(person.getFavoriteNumber()).as("'favorite number' (protected method for a Number)").isEqualTo(42);
assertThat(invokeGetterMethod(person, "getId")).isEqualTo(Long.valueOf(1)); assertThat(invokeGetterMethod(person, "getId")).isEqualTo(1L);
assertThat(invokeGetterMethod(person, "getName")).isEqualTo("Jerry"); assertThat(invokeGetterMethod(person, "getName")).isEqualTo("Jerry");
assertThat(invokeGetterMethod(person, "getAge")).isEqualTo(Integer.valueOf(33)); assertThat(invokeGetterMethod(person, "getAge")).isEqualTo(33);
assertThat(invokeGetterMethod(person, "getEyeColor")).isEqualTo("green"); assertThat(invokeGetterMethod(person, "getEyeColor")).isEqualTo("green");
assertThat(invokeGetterMethod(person, "likesPets")).isEqualTo(Boolean.FALSE); assertThat(invokeGetterMethod(person, "likesPets")).isEqualTo(Boolean.FALSE);
assertThat(invokeGetterMethod(person, "getFavoriteNumber")).isEqualTo(Integer.valueOf(42)); assertThat(invokeGetterMethod(person, "getFavoriteNumber")).isEqualTo(42);
} }
@Test @Test
void invokeSetterMethodAndInvokeGetterMethodWithJavaBeanPropertyNames() throws Exception { void invokeSetterMethodAndInvokeGetterMethodWithJavaBeanPropertyNames() throws Exception {
invokeSetterMethod(person, "id", Long.valueOf(99), long.class); invokeSetterMethod(person, "id", 99L, long.class);
invokeSetterMethod(person, "name", "Tom"); invokeSetterMethod(person, "name", "Tom");
invokeSetterMethod(person, "age", Integer.valueOf(42)); invokeSetterMethod(person, "age", 42);
invokeSetterMethod(person, "eyeColor", "blue", String.class); invokeSetterMethod(person, "eyeColor", "blue", String.class);
invokeSetterMethod(person, "likesPets", Boolean.TRUE); invokeSetterMethod(person, "likesPets", Boolean.TRUE);
invokeSetterMethod(person, "favoriteNumber", PI, Number.class); invokeSetterMethod(person, "favoriteNumber", PI, Number.class);
@ -287,9 +287,9 @@ class ReflectionTestUtilsTests {
assertThat(person.likesPets()).as("'likes pets' flag (protected method for a boolean)").isTrue(); assertThat(person.likesPets()).as("'likes pets' flag (protected method for a boolean)").isTrue();
assertThat(person.getFavoriteNumber()).as("'favorite number' (protected method for a Number)").isEqualTo(PI); assertThat(person.getFavoriteNumber()).as("'favorite number' (protected method for a Number)").isEqualTo(PI);
assertThat(invokeGetterMethod(person, "id")).isEqualTo(Long.valueOf(99)); assertThat(invokeGetterMethod(person, "id")).isEqualTo(99L);
assertThat(invokeGetterMethod(person, "name")).isEqualTo("Tom"); assertThat(invokeGetterMethod(person, "name")).isEqualTo("Tom");
assertThat(invokeGetterMethod(person, "age")).isEqualTo(Integer.valueOf(42)); assertThat(invokeGetterMethod(person, "age")).isEqualTo(42);
assertThat(invokeGetterMethod(person, "eyeColor")).isEqualTo("blue"); assertThat(invokeGetterMethod(person, "eyeColor")).isEqualTo("blue");
assertThat(invokeGetterMethod(person, "likesPets")).isEqualTo(Boolean.TRUE); assertThat(invokeGetterMethod(person, "likesPets")).isEqualTo(Boolean.TRUE);
assertThat(invokeGetterMethod(person, "favoriteNumber")).isEqualTo(PI); assertThat(invokeGetterMethod(person, "favoriteNumber")).isEqualTo(PI);
@ -349,7 +349,7 @@ class ReflectionTestUtilsTests {
assertThat(component.getText()).as("text").isNull(); assertThat(component.getText()).as("text").isNull();
// Simulate autowiring a configuration method // Simulate autowiring a configuration method
invokeMethod(component, "configure", Integer.valueOf(42), "enigma"); invokeMethod(component, "configure", 42, "enigma");
assertThat(component.getNumber()).as("number should have been configured").isEqualTo(Integer.valueOf(42)); assertThat(component.getNumber()).as("number should have been configured").isEqualTo(Integer.valueOf(42));
assertThat(component.getText()).as("text should have been configured").isEqualTo("enigma"); assertThat(component.getText()).as("text should have been configured").isEqualTo("enigma");
@ -380,14 +380,14 @@ class ReflectionTestUtilsTests {
@Test @Test
void invokeMethodWithTooFewArguments() { void invokeMethodWithTooFewArguments() {
assertThatIllegalStateException() assertThatIllegalStateException()
.isThrownBy(() -> invokeMethod(component, "configure", Integer.valueOf(42))) .isThrownBy(() -> invokeMethod(component, "configure", 42))
.withMessageStartingWith("Method not found"); .withMessageStartingWith("Method not found");
} }
@Test @Test
void invokeMethodWithTooManyArguments() { void invokeMethodWithTooManyArguments() {
assertThatIllegalStateException() assertThatIllegalStateException()
.isThrownBy(() -> invokeMethod(component, "configure", Integer.valueOf(42), "enigma", "baz", "quux")) .isThrownBy(() -> invokeMethod(component, "configure", 42, "enigma", "baz", "quux"))
.withMessageStartingWith("Method not found"); .withMessageStartingWith("Method not found");
} }
@ -406,7 +406,7 @@ class ReflectionTestUtilsTests {
@Test // SPR-14363 @Test // SPR-14363
void invokeMethodOnLegacyEntityWithSideEffectsInToString() { void invokeMethodOnLegacyEntityWithSideEffectsInToString() {
invokeMethod(entity, "configure", Integer.valueOf(42), "enigma"); invokeMethod(entity, "configure", 42, "enigma");
assertThat(entity.getNumber()).as("number should have been configured").isEqualTo(Integer.valueOf(42)); assertThat(entity.getNumber()).as("number should have been configured").isEqualTo(Integer.valueOf(42));
assertThat(entity.getText()).as("text should have been configured").isEqualTo("enigma"); assertThat(entity.getText()).as("text should have been configured").isEqualTo("enigma");
} }

8
spring-test/src/test/java/org/springframework/test/web/client/MockRestServiceServerTests.java

@ -183,9 +183,11 @@ public class MockRestServiceServerTests {
this.restTemplate.getForObject("/foo", Void.class); this.restTemplate.getForObject("/foo", Void.class);
assertThatThrownBy(() -> server1.verify(Duration.ofMillis(100))).hasMessage( assertThatThrownBy(() -> server1.verify(Duration.ofMillis(100))).hasMessage(
"Further request(s) expected leaving 1 unsatisfied expectation(s).\n" + """
"1 request(s) executed:\n" + Further request(s) expected leaving 1 unsatisfied expectation(s).
"GET /foo, headers: [Accept:\"application/json, application/*+json\"]\n"); 1 request(s) executed:
GET /foo, headers: [Accept:"application/json, application/*+json"]
""");
MockRestServiceServer server2 = builder.build(); MockRestServiceServer server2 = builder.build();
server2.expect(requestTo("/foo")).andRespond(withSuccess()); server2.expect(requestTo("/foo")).andRespond(withSuccess());

47
spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java

@ -55,8 +55,10 @@ public class SimpleRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/foo")); this.manager.validateRequest(createRequest(GET, "/foo"));
} }
catch (AssertionError error) { catch (AssertionError error) {
assertThat(error.getMessage()).isEqualTo(("No further requests expected: HTTP GET /foo\n" + assertThat(error.getMessage()).isEqualTo(("""
"0 request(s) executed.\n")); No further requests expected: HTTP GET /foo
0 request(s) executed.
"""));
} }
} }
@ -83,10 +85,12 @@ public class SimpleRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/bar")); this.manager.validateRequest(createRequest(GET, "/bar"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.validateRequest(createRequest(GET, "/baz"))) this.manager.validateRequest(createRequest(GET, "/baz")))
.withMessage("No further requests expected: HTTP GET /baz\n" + .withMessage("""
"2 request(s) executed:\n" + No further requests expected: HTTP GET /baz
"GET /foo\n" + 2 request(s) executed:
"GET /bar\n"); GET /foo
GET /bar
""");
} }
@Test @Test
@ -96,8 +100,11 @@ public class SimpleRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/foo")); this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.verify()) this.manager.verify())
.withMessage("Further request(s) expected leaving 1 unsatisfied expectation(s).\n" + .withMessage("""
"1 request(s) executed:\nGET /foo\n"); Further request(s) expected leaving 1 unsatisfied expectation(s).
1 request(s) executed:
GET /foo
""");
} }
@Test @Test
@ -124,12 +131,14 @@ public class SimpleRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/bar")); this.manager.validateRequest(createRequest(GET, "/bar"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.validateRequest(createRequest(GET, "/foo"))) this.manager.validateRequest(createRequest(GET, "/foo")))
.withMessage("No further requests expected: HTTP GET /foo\n" + .withMessage("""
"4 request(s) executed:\n" + No further requests expected: HTTP GET /foo
"GET /foo\n" + 4 request(s) executed:
"GET /bar\n" + GET /foo
"GET /foo\n" + GET /bar
"GET /bar\n"); GET /foo
GET /bar
""");
} }
@Test @Test
@ -141,10 +150,12 @@ public class SimpleRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/foo")); this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.verify()) this.manager.verify())
.withMessageContaining("3 request(s) executed:\n" + .withMessageContaining("""
"GET /foo\n" + 3 request(s) executed:
"GET /bar\n" + GET /foo
"GET /foo\n"); GET /bar
GET /foo
""");
} }
@Test @Test

30
spring-test/src/test/java/org/springframework/test/web/client/UnorderedRequestExpectationManagerTests.java

@ -52,8 +52,10 @@ public class UnorderedRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/foo")); this.manager.validateRequest(createRequest(GET, "/foo"));
} }
catch (AssertionError error) { catch (AssertionError error) {
assertThat(error.getMessage()).isEqualTo(("No further requests expected: HTTP GET /foo\n" + assertThat(error.getMessage()).isEqualTo(("""
"0 request(s) executed.\n")); No further requests expected: HTTP GET /foo
0 request(s) executed.
"""));
} }
} }
@ -94,12 +96,14 @@ public class UnorderedRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/foo")); this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
this.manager.validateRequest(createRequest(GET, "/foo"))) this.manager.validateRequest(createRequest(GET, "/foo")))
.withMessage("No further requests expected: HTTP GET /foo\n" + .withMessage("""
"4 request(s) executed:\n" + No further requests expected: HTTP GET /foo
"GET /bar\n" + 4 request(s) executed:
"GET /foo\n" + GET /bar
"GET /bar\n" + GET /foo
"GET /foo\n"); GET /bar
GET /foo
""");
} }
@Test @Test
@ -111,10 +115,12 @@ public class UnorderedRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/foo")); this.manager.validateRequest(createRequest(GET, "/foo"));
assertThatExceptionOfType(AssertionError.class) assertThatExceptionOfType(AssertionError.class)
.isThrownBy(this.manager::verify) .isThrownBy(this.manager::verify)
.withMessageContaining("3 request(s) executed:\n" + .withMessageContaining("""
"GET /bar\n" + 3 request(s) executed:
"GET /foo\n" + GET /bar
"GET /foo\n"); GET /foo
GET /foo
""");
} }

7
spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/SoftAssertionTests.java

@ -56,9 +56,10 @@ class SoftAssertionTests {
responseSpec -> responseSpec.expectBody(String.class).isEqualTo("bogus") responseSpec -> responseSpec.expectBody(String.class).isEqualTo("bogus")
) )
) )
.withMessage("Multiple Exceptions (2):\n" + .withMessage("""
"Status expected:<400 BAD_REQUEST> but was:<200 OK>\n" + Multiple Exceptions (2):
"Response body expected:<bogus> but was:<hello>"); Status expected:<400 BAD_REQUEST> but was:<200 OK>
Response body expected:<bogus> but was:<hello>""");
} }

3
spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/DelegatingWebConnectionTests.java

@ -17,6 +17,7 @@
package org.springframework.test.web.servlet.htmlunit; package org.springframework.test.web.servlet.htmlunit;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import com.gargoylesoftware.htmlunit.HttpWebConnection; import com.gargoylesoftware.htmlunit.HttpWebConnection;
@ -79,7 +80,7 @@ public class DelegatingWebConnectionTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { public void setup() throws Exception {
request = new WebRequest(new URL("http://localhost/")); request = new WebRequest(new URL("http://localhost/"));
WebResponseData data = new WebResponseData("".getBytes("UTF-8"), 200, "", Collections.emptyList()); WebResponseData data = new WebResponseData("".getBytes(StandardCharsets.UTF_8), 200, "", Collections.emptyList());
expectedResponse = new WebResponse(data, request, 100L); expectedResponse = new WebResponse(data, request, 100L);
webConnection = new DelegatingWebConnection(defaultConnection, webConnection = new DelegatingWebConnection(defaultConnection,
new DelegateWebConnection(matcher1, connection1), new DelegateWebConnection(matcher2, connection2)); new DelegateWebConnection(matcher1, connection1), new DelegateWebConnection(matcher2, connection2));

2
spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java

@ -414,7 +414,7 @@ class MockHttpServletRequestBuilderTests {
@Test @Test
void body() throws IOException { void body() throws IOException {
byte[] body = "Hello World".getBytes("UTF-8"); byte[] body = "Hello World".getBytes(StandardCharsets.UTF_8);
this.builder.content(body); this.builder.content(body);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);

6
spring-test/src/test/java/org/springframework/test/web/servlet/result/ContentResultMatchersTests.java

@ -46,7 +46,7 @@ public class ContentResultMatchersTests {
@Test @Test
public void string() throws Exception { public void string() throws Exception {
new ContentResultMatchers().string(new String(CONTENT.getBytes("UTF-8"))).match(getStubMvcResult(CONTENT)); new ContentResultMatchers().string(new String(CONTENT.getBytes(StandardCharsets.UTF_8))).match(getStubMvcResult(CONTENT));
} }
@Test @Test
@ -57,7 +57,7 @@ public class ContentResultMatchersTests {
@Test @Test
public void stringMatcher() throws Exception { public void stringMatcher() throws Exception {
String content = new String(CONTENT.getBytes("UTF-8")); String content = new String(CONTENT.getBytes(StandardCharsets.UTF_8));
new ContentResultMatchers().string(Matchers.equalTo(content)).match(getStubMvcResult(CONTENT)); new ContentResultMatchers().string(Matchers.equalTo(content)).match(getStubMvcResult(CONTENT));
} }
@ -69,7 +69,7 @@ public class ContentResultMatchersTests {
@Test @Test
public void bytes() throws Exception { public void bytes() throws Exception {
new ContentResultMatchers().bytes(CONTENT.getBytes("UTF-8")).match(getStubMvcResult(CONTENT)); new ContentResultMatchers().bytes(CONTENT.getBytes(StandardCharsets.UTF_8)).match(getStubMvcResult(CONTENT));
} }
@Test @Test

4
spring-test/src/test/java/org/springframework/test/web/servlet/result/JsonPathResultMatchersTests.java

@ -302,7 +302,7 @@ public class JsonPathResultMatchersTests {
public void prefixWithPayloadNotLongEnough() throws Exception { public void prefixWithPayloadNotLongEnough() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json"); response.addHeader("Content-Type", "application/json");
response.getWriter().print(new String("test".getBytes("ISO-8859-1"))); response.getWriter().print(new String("test".getBytes(StandardCharsets.ISO_8859_1)));
StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response); StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response);
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
@ -312,7 +312,7 @@ public class JsonPathResultMatchersTests {
private StubMvcResult createPrefixedStubMvcResult(String jsonPrefix) throws Exception { private StubMvcResult createPrefixedStubMvcResult(String jsonPrefix) throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json"); response.addHeader("Content-Type", "application/json");
response.getWriter().print(jsonPrefix + new String(RESPONSE_CONTENT.getBytes("ISO-8859-1"))); response.getWriter().print(jsonPrefix + new String(RESPONSE_CONTENT.getBytes(StandardCharsets.ISO_8859_1)));
return new StubMvcResult(null, null, null, null, null, null, response); return new StubMvcResult(null, null, null, null, null, null, response);
} }

9
spring-test/src/test/java/org/springframework/test/web/servlet/result/PrintingResultHandlerTests.java

@ -17,6 +17,7 @@
package org.springframework.test.web.servlet.result; package org.springframework.test.web.servlet.result;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -74,7 +75,7 @@ public class PrintingResultHandlerTests {
this.request.addHeader("header", "headerValue"); this.request.addHeader("header", "headerValue");
this.request.setCharacterEncoding("UTF-16"); this.request.setCharacterEncoding("UTF-16");
String palindrome = "ablE was I ere I saw Elba"; String palindrome = "ablE was I ere I saw Elba";
byte[] bytes = palindrome.getBytes("UTF-16"); byte[] bytes = palindrome.getBytes(StandardCharsets.UTF_16);
this.request.setContent(bytes); this.request.setContent(bytes);
this.request.getSession().setAttribute("foo", "bar"); this.request.getSession().setAttribute("foo", "bar");
@ -100,7 +101,7 @@ public class PrintingResultHandlerTests {
this.request.addHeader("header", "headerValue"); this.request.addHeader("header", "headerValue");
this.request.setCharacterEncoding("UTF-16"); this.request.setCharacterEncoding("UTF-16");
String palindrome = "ablE was I ere I saw Elba"; String palindrome = "ablE was I ere I saw Elba";
byte[] bytes = palindrome.getBytes("UTF-16"); byte[] bytes = palindrome.getBytes(StandardCharsets.UTF_16);
this.request.setContent(bytes); this.request.setContent(bytes);
this.handler.handle(this.mvcResult); this.handler.handle(this.mvcResult);
@ -124,7 +125,7 @@ public class PrintingResultHandlerTests {
this.request.addHeader("header", "headerValue"); this.request.addHeader("header", "headerValue");
this.request.setCharacterEncoding("UTF-16"); this.request.setCharacterEncoding("UTF-16");
String palindrome = "ablE was I ere I saw Elba"; String palindrome = "ablE was I ere I saw Elba";
byte[] bytes = palindrome.getBytes("UTF-16"); byte[] bytes = palindrome.getBytes(StandardCharsets.UTF_16);
this.request.setContent(bytes); this.request.setContent(bytes);
this.request.setSession(Mockito.mock(HttpSession.class)); this.request.setSession(Mockito.mock(HttpSession.class));
@ -204,7 +205,7 @@ public class PrintingResultHandlerTests {
@Test @Test
public void printRequestWithCharacterEncoding() throws Exception { public void printRequestWithCharacterEncoding() throws Exception {
this.request.setCharacterEncoding("UTF-8"); this.request.setCharacterEncoding("UTF-8");
this.request.setContent("text".getBytes("UTF-8")); this.request.setContent("text".getBytes(StandardCharsets.UTF_8));
this.handler.handle(this.mvcResult); this.handler.handle(this.mvcResult);

23
spring-test/src/test/java/org/springframework/test/web/servlet/result/StatusResultMatchersTests.java

@ -85,23 +85,12 @@ public class StatusResultMatchersTests {
response.setStatus(status.value()); response.setStatus(status.value());
MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response); MvcResult mvcResult = new StubMvcResult(request, null, null, null, null, null, response);
switch (status.series().value()) { switch (status.series().value()) {
case 1: case 1 -> this.matchers.is1xxInformational().match(mvcResult);
this.matchers.is1xxInformational().match(mvcResult); case 2 -> this.matchers.is2xxSuccessful().match(mvcResult);
break; case 3 -> this.matchers.is3xxRedirection().match(mvcResult);
case 2: case 4 -> this.matchers.is4xxClientError().match(mvcResult);
this.matchers.is2xxSuccessful().match(mvcResult); case 5 -> this.matchers.is5xxServerError().match(mvcResult);
break; default -> fail("Unexpected range for status code value " + status);
case 3:
this.matchers.is3xxRedirection().match(mvcResult);
break;
case 4:
this.matchers.is4xxClientError().match(mvcResult);
break;
case 5:
this.matchers.is5xxServerError().match(mvcResult);
break;
default:
fail("Unexpected range for status code value " + status);
} }
} }
} }

13
spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/ExceptionHandlerTests.java

@ -173,14 +173,11 @@ class ExceptionHandlerTests {
@GetMapping("/person/{name}") @GetMapping("/person/{name}")
Person get(@PathVariable String name) { Person get(@PathVariable String name) {
switch (name) { return switch (name) {
case "Luke": case "Luke" -> throw new IllegalArgumentException();
throw new IllegalArgumentException(); case "Leia" -> throw new IllegalStateException();
case "Leia": default -> new Person("Yoda");
throw new IllegalStateException(); };
default:
return new Person("Yoda");
}
} }
@ExceptionHandler @ExceptionHandler

11
spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/XpathAssertionTests.java

@ -224,11 +224,12 @@ public class XpathAssertionTests {
@RequestMapping(value = "/blog.atom", method = {GET, HEAD}) @RequestMapping(value = "/blog.atom", method = {GET, HEAD})
@ResponseBody @ResponseBody
public String listPublishedPosts() { public String listPublishedPosts() {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" return """
+ "<feed xmlns=\"http://www.w3.org/2005/Atom\">\r\n" <?xml version="1.0" encoding="UTF-8"?>
+ " <title>Test Feed</title>\r\n" <feed xmlns="http://www.w3.org/2005/Atom">
+ " <icon>https://www.example.com/favicon.ico</icon>\r\n" <title>Test Feed</title>
+ "</feed>\r\n\r\n"; <icon>https://www.example.com/favicon.ico</icon>
</feed>""".replaceAll("\n", "\r\n");
} }
} }

13
spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/ExceptionHandlerTests.java

@ -152,14 +152,11 @@ public class ExceptionHandlerTests {
@GetMapping("/person/{name}") @GetMapping("/person/{name}")
Person get(@PathVariable String name) { Person get(@PathVariable String name) {
switch (name) { return switch (name) {
case "Luke": case "Luke" -> throw new IllegalArgumentException();
throw new IllegalArgumentException(); case "Leia" -> throw new IllegalStateException();
case "Leia": default -> new Person("Yoda");
throw new IllegalStateException(); };
default:
return new Person("Yoda");
}
} }
@ExceptionHandler @ExceptionHandler

18
spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/MultipartControllerTests.java

@ -70,18 +70,12 @@ class MultipartControllerTests {
byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8); byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8);
MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json); MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json);
MockMultipartHttpServletRequestBuilder requestBuilder; MockMultipartHttpServletRequestBuilder requestBuilder = switch (url) {
switch (url) { case "/multipartfile" -> multipart(url).file(new MockMultipartFile("file", "orig", null, fileContent));
case "/multipartfile": case "/multipartfile-via-put" ->
requestBuilder = multipart(url).file(new MockMultipartFile("file", "orig", null, fileContent)); multipart(HttpMethod.PUT, url).file(new MockMultipartFile("file", "orig", null, fileContent));
break; default -> multipart(url).part(new MockPart("part", "orig", fileContent));
case "/multipartfile-via-put": };
requestBuilder = multipart(HttpMethod.PUT, url).file(new MockMultipartFile("file", "orig", null, fileContent));
break;
default:
requestBuilder = multipart(url).part(new MockPart("part", "orig", fileContent));
break;
}
standaloneSetup(new MultipartController()).build() standaloneSetup(new MultipartController()).build()
.perform(requestBuilder.file(jsonPart)) .perform(requestBuilder.file(jsonPart))

2
spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resulthandlers/PrintingResultHandlerSmokeTests.java

@ -68,7 +68,7 @@ public class PrintingResultHandlerSmokeTests {
System.out.println(); System.out.println();
System.out.println("==============================================================="); System.out.println("===============================================================");
System.out.println(writer.toString()); System.out.println(writer);
} }

8
spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java

@ -79,10 +79,10 @@ public class ContentAssertionTests {
@Test @Test
void contentAsBytes() throws Exception { void contentAsBytes() throws Exception {
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
.andExpect(content().bytes("Hello world!".getBytes("ISO-8859-1"))); .andExpect(content().bytes("Hello world!".getBytes(StandardCharsets.ISO_8859_1)));
this.mockMvc.perform(get("/handleUtf8")) this.mockMvc.perform(get("/handleUtf8"))
.andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8"))); .andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes(StandardCharsets.UTF_8)));
} }
@Test @Test
@ -103,11 +103,11 @@ public class ContentAssertionTests {
this.mockMvc.perform(get("/handleUtf8")) this.mockMvc.perform(get("/handleUtf8"))
.andExpect(content().encoding("UTF-8")) .andExpect(content().encoding("UTF-8"))
.andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8"))); .andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes(StandardCharsets.UTF_8)));
this.mockMvc.perform(get("/handleUtf8")) this.mockMvc.perform(get("/handleUtf8"))
.andExpect(content().encoding(StandardCharsets.UTF_8)) .andExpect(content().encoding(StandardCharsets.UTF_8))
.andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8"))); .andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes(StandardCharsets.UTF_8)));
} }

11
spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/XpathAssertionTests.java

@ -228,11 +228,12 @@ public class XpathAssertionTests {
@RequestMapping(value="/blog.atom", method = { GET, HEAD }) @RequestMapping(value="/blog.atom", method = { GET, HEAD })
@ResponseBody @ResponseBody
public String listPublishedPosts() { public String listPublishedPosts() {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" return """
+ "<feed xmlns=\"http://www.w3.org/2005/Atom\">\r\n" <?xml version="1.0" encoding="UTF-8"?>
+ " <title>Test Feed</title>\r\n" <feed xmlns="http://www.w3.org/2005/Atom">
+ " <icon>https://www.example.com/favicon.ico</icon>\r\n" <title>Test Feed</title>
+ "</feed>\r\n\r\n"; <icon>https://www.example.com/favicon.ico</icon>
</feed>""".replaceAll("\n", "\r\n");
} }
} }

18
spring-test/src/test/kotlin/org/springframework/test/web/servlet/MockMvcExtensionsTests.kt

@ -16,21 +16,27 @@
package org.springframework.test.web.servlet package org.springframework.test.web.servlet
import org.assertj.core.api.Assertions.* import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.hamcrest.CoreMatchers import org.hamcrest.CoreMatchers
import org.hamcrest.Matcher
import org.hamcrest.Matchers
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import org.springframework.http.HttpMethod import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus
import org.springframework.http.MediaType.* import org.springframework.http.MediaType.APPLICATION_ATOM_XML
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.http.MediaType.APPLICATION_XML
import org.springframework.test.web.Person import org.springframework.test.web.Person
import org.springframework.test.web.servlet.setup.MockMvcBuilders import org.springframework.test.web.servlet.setup.MockMvcBuilders
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.ModelAndView
import reactor.core.publisher.Mono import reactor.core.publisher.Mono
import java.security.Principal import java.security.Principal
import java.util.* import java.util.Locale
/** /**
* [MockMvc] DSL tests that verifies builder, actions and expect blocks. * [MockMvc] DSL tests that verifies builder, actions and expect blocks.

Loading…
Cancel
Save