From e73344fc7183631bc86ef9273afbbdce9414e629 Mon Sep 17 00:00:00 2001 From: Drummond Dawson Date: Thu, 3 Oct 2019 20:38:23 -0400 Subject: [PATCH] Introduce sessionAttributeDoesNotExist in RequestResultMatchers Analogous to the attributeDoesNotExist() method in ModelResultMatchers, this commit introduces a new sessionAttributeDoesNotExist() method in RequestResultMatchers which asserts that the given attributes are null in the HttpSession. Closes gh-23756 --- .../web/servlet/result/RequestResultMatchers.java | 14 ++++++++++++++ .../SessionAttributeAssertionTests.java | 6 ++++++ 2 files changed, 20 insertions(+) diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java index 22d073f8c2f..4d7dec542d6 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java @@ -31,6 +31,7 @@ import org.springframework.web.context.request.async.WebAsyncTask; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.util.AssertionErrors.assertEquals; +import static org.springframework.test.util.AssertionErrors.assertTrue; /** * Factory for assertions on the request. @@ -150,6 +151,19 @@ public class RequestResultMatchers { }; } + /** + * Assert the given session attributes do not exist. + */ + public ResultMatcher sessionAttributeDoesNotExist(String... names) { + return result -> { + HttpSession session = result.getRequest().getSession(); + Assert.state(session != null, "No HttpSession"); + for (String name : names) { + assertTrue("Session attribute '" + name + "' exists", session.getAttribute(name) == null); + } + }; + } + private static void assertAsyncStarted(HttpServletRequest request) { assertEquals("Async started", true, request.isAsyncStarted()); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/SessionAttributeAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/SessionAttributeAssertionTests.java index c1280c4d98e..e65be2e0cb2 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/SessionAttributeAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/SessionAttributeAssertionTests.java @@ -65,6 +65,12 @@ public class SessionAttributeAssertionTests { .andExpect(request().sessionAttribute("locale", notNullValue())); } + @Test + public void testSessionAttributeDoesNotExist() throws Exception { + this.mockMvc.perform(get("/")) + .andExpect(request().sessionAttributeDoesNotExist("myAttr1", "myAttr2")); + } + @Controller @SessionAttributes("locale")