From 52006b71bcd5812c868420b132b357fadf0e728e Mon Sep 17 00:00:00 2001 From: Brian Clozel Date: Wed, 11 Dec 2024 16:00:41 +0100 Subject: [PATCH] Support Servlet error message in MockMvc assertions Prior to this commit, `MockMvc` would support checking for the Servlet error message as the "response status reason". While this error message can be driven with the `@ResponseStatus` annotation, this message is not technically the HTTP status reason listed on the response status line. This message is provided by the Servlet container in the error page when the `response.sendError(int, String)` method is used. This commit adds the missing `mvc.get().uri("/error/message")).hasErrorMessage("error message")` assertion to check for this Servlet error message. Closes gh-34016 --- .../AbstractMockHttpServletResponseAssert.java | 13 +++++++++++++ ...bstractMockHttpServletResponseAssertTests.java | 7 +++++++ .../assertj/MockMvcTesterIntegrationTests.java | 15 +++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/assertj/AbstractMockHttpServletResponseAssert.java b/spring-test/src/main/java/org/springframework/test/web/servlet/assertj/AbstractMockHttpServletResponseAssert.java index a6c98a6331e..6fc0dbd79af 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/assertj/AbstractMockHttpServletResponseAssert.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/assertj/AbstractMockHttpServletResponseAssert.java @@ -22,6 +22,7 @@ import org.assertj.core.api.AbstractByteArrayAssert; import org.assertj.core.api.AbstractStringAssert; import org.assertj.core.api.Assertions; import org.assertj.core.api.ByteArrayAssert; +import org.assertj.core.api.StringAssert; import org.springframework.lang.Nullable; import org.springframework.mock.web.MockHttpServletResponse; @@ -163,4 +164,16 @@ public abstract class AbstractMockHttpServletResponseAssert assertThat(result).hasRedirectedUrl("test")); } + @Test + void assertErrorMessageWithUnresolvedException() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(mvc.get().uri("/error/message")).hasErrorMessage("invalid")) + .withMessageContainingAll("[Servlet error message]", "invalid", "expected error message"); + } + @Test void assertRequestWithUnresolvedException() { testAssertionFailureWithUnresolvableException( @@ -798,6 +806,13 @@ public class MockMvcTesterIntegrationTests { public String validation(@PathVariable @Size(max = 4) String id) { return "Hello " + id; } + + @GetMapping("/error/message") + @ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "expected error message") + public void errorMessage() { + + } + } }