diff --git a/spring-test/src/main/java/org/springframework/test/util/AssertionErrors.java b/spring-test/src/main/java/org/springframework/test/util/AssertionErrors.java index 1865847673..7c76c64599 100644 --- a/spring-test/src/main/java/org/springframework/test/util/AssertionErrors.java +++ b/spring-test/src/main/java/org/springframework/test/util/AssertionErrors.java @@ -71,6 +71,30 @@ public abstract class AssertionErrors { } } + /** + * Assert the given condition is {@code false} and raise an + * {@link AssertionError} otherwise. + * @param message a message that describes the reason for the failure + * @param condition the condition to test for + * @since 5.2.1 + */ + public static void assertFalse(String message, boolean condition) { + if (condition) { + fail(message); + } + } + + /** + * Assert that the given object is {@code null} and raise an + * {@link AssertionError} otherwise. + * @param message a message that describes the reason for the failure + * @param object the object to check + * @since 5.2.1 + */ + public static void assertNull(String message, @Nullable Object object) { + assertTrue(message, object == null); + } + /** * Assert that the given object is not {@code null} and raise an * {@link AssertionError} otherwise. diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/CookieResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/CookieResultMatchers.java index 792753db9c..a548731f2a 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/CookieResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/CookieResultMatchers.java @@ -26,7 +26,7 @@ import org.springframework.test.web.servlet.ResultMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.util.AssertionErrors.assertEquals; import static org.springframework.test.util.AssertionErrors.assertNotNull; -import static org.springframework.test.util.AssertionErrors.assertTrue; +import static org.springframework.test.util.AssertionErrors.assertNull; /** * Factory for response cookie assertions. @@ -83,7 +83,7 @@ public class CookieResultMatchers { public ResultMatcher doesNotExist(String name) { return result -> { Cookie cookie = result.getResponse().getCookie(name); - assertTrue("Unexpected cookie with name '" + name + "'", cookie == null); + assertNull("Unexpected cookie with name '" + name + "'", cookie); }; } @@ -98,7 +98,7 @@ public class CookieResultMatchers { } /** - * Assert a cookie's maxAge value. + * Assert a cookie's maxAge. */ public ResultMatcher maxAge(String name, int maxAge) { return result -> { @@ -108,7 +108,7 @@ public class CookieResultMatchers { } /** - * Assert a cookie path with a Hamcrest {@link Matcher}. + * Assert a cookie's path with a Hamcrest {@link Matcher}. */ public ResultMatcher path(String name, Matcher matcher) { return result -> { @@ -117,6 +117,9 @@ public class CookieResultMatchers { }; } + /** + * Assert a cookie's path. + */ public ResultMatcher path(String name, String path) { return result -> { Cookie cookie = getCookie(result, name); @@ -135,7 +138,7 @@ public class CookieResultMatchers { } /** - * Assert a cookie's domain value. + * Assert a cookie's domain. */ public ResultMatcher domain(String name, String domain) { return result -> { @@ -155,7 +158,7 @@ public class CookieResultMatchers { } /** - * Assert a cookie's comment value. + * Assert a cookie's comment. */ public ResultMatcher comment(String name, String comment) { return result -> { @@ -175,7 +178,7 @@ public class CookieResultMatchers { } /** - * Assert a cookie's version value. + * Assert a cookie's version. */ public ResultMatcher version(String name, int version) { return result -> { diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java index 72b6db0a29..5e79c08216 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java @@ -73,7 +73,7 @@ public class FlashAttributeResultMatchers { * Assert the number of flash attributes. */ public ResultMatcher attributeCount(int count) { - return result -> assertEquals("FlashMap size must be " + count, count, result.getFlashMap().size()); + return result -> assertEquals("FlashMap size", count, result.getFlashMap().size()); } } diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java index e26a777f65..60203db6d4 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java @@ -27,6 +27,7 @@ import org.springframework.test.web.servlet.ResultMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.util.AssertionErrors.assertEquals; +import static org.springframework.test.util.AssertionErrors.assertFalse; import static org.springframework.test.util.AssertionErrors.assertNotNull; import static org.springframework.test.util.AssertionErrors.assertTrue; @@ -103,8 +104,8 @@ public class HeaderResultMatchers { * @since 4.0 */ public ResultMatcher doesNotExist(String name) { - return result -> assertTrue("Response should not contain header '" + name + "'", - !result.getResponse().containsHeader(name)); + return result -> assertFalse("Response should not contain header '" + name + "'", + result.getResponse().containsHeader(name)); } /** diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java b/spring-test/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java index eff1666f80..507fd7b87b 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java @@ -28,7 +28,9 @@ import org.springframework.web.servlet.ModelAndView; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.util.AssertionErrors.assertEquals; +import static org.springframework.test.util.AssertionErrors.assertFalse; import static org.springframework.test.util.AssertionErrors.assertNotNull; +import static org.springframework.test.util.AssertionErrors.assertNull; import static org.springframework.test.util.AssertionErrors.assertTrue; /** @@ -91,7 +93,7 @@ public class ModelResultMatchers { return result -> { ModelAndView mav = getModelAndView(result); for (String name : names) { - assertTrue("Model attribute '" + name + "' exists", mav.getModel().get(name) == null); + assertNull("Model attribute '" + name + "' exists", mav.getModel().get(name)); } }; } @@ -103,7 +105,7 @@ public class ModelResultMatchers { return result -> { ModelAndView mav = getModelAndView(result); Errors errors = getBindingResult(mav, name); - assertEquals("Binding/validation error count for attribute '" + name + "', ", + assertEquals("Binding/validation error count for attribute '" + name + "',", expectedCount, errors.getErrorCount()); }; } @@ -129,8 +131,8 @@ public class ModelResultMatchers { ModelAndView mav = getModelAndView(mvcResult); for (String name : names) { BindingResult result = getBindingResult(mav, name); - assertTrue("Unexpected errors for attribute '" + name + "': " + result.getAllErrors(), - !result.hasErrors()); + assertFalse("Unexpected errors for attribute '" + name + "': " + result.getAllErrors(), + result.hasErrors()); } }; } @@ -212,7 +214,7 @@ public class ModelResultMatchers { ModelAndView mav = getModelAndView(result); for (Object value : mav.getModel().values()) { if (value instanceof Errors) { - assertTrue("Unexpected binding/validation errors: " + value, !((Errors) value).hasErrors()); + assertFalse("Unexpected binding/validation errors: " + value, ((Errors) value).hasErrors()); } } }; 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 f48de0d4ba..067e284820 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,8 @@ 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.assertFalse; +import static org.springframework.test.util.AssertionErrors.assertNull; import static org.springframework.test.util.AssertionErrors.assertTrue; /** @@ -57,16 +59,15 @@ public class RequestResultMatchers { * Assert whether asynchronous processing started, usually as a result of a * controller method returning {@link Callable} or {@link DeferredResult}. *

The test will await the completion of a {@code Callable} so that - * {@link #asyncResult(Matcher)} can be used to assert the resulting value. - * Neither a {@code Callable} nor a {@code DeferredResult} will complete + * {@link #asyncResult(Matcher)} or {@link #asyncResult(Object)} can be used + * to assert the resulting value. + *

Neither a {@code Callable} nor a {@code DeferredResult} will complete * processing all the way since a {@link MockHttpServletRequest} does not * perform asynchronous dispatches. + * @see #asyncNotStarted() */ public ResultMatcher asyncStarted() { - return result -> { - HttpServletRequest request = result.getRequest(); - assertAsyncStarted(request); - }; + return result -> assertAsyncStarted(result.getRequest()); } /** @@ -74,10 +75,7 @@ public class RequestResultMatchers { * @see #asyncStarted() */ public ResultMatcher asyncNotStarted() { - return result -> { - HttpServletRequest request = result.getRequest(); - assertEquals("Async started", false, request.isAsyncStarted()); - }; + return result -> assertFalse("Async started", result.getRequest().isAsyncStarted()); } /** @@ -160,13 +158,13 @@ public class RequestResultMatchers { HttpSession session = result.getRequest().getSession(); Assert.state(session != null, "No HttpSession"); for (String name : names) { - assertTrue("Session attribute '" + name + "' exists", session.getAttribute(name) == null); + assertNull("Session attribute '" + name + "' exists", session.getAttribute(name)); } }; } private static void assertAsyncStarted(HttpServletRequest request) { - assertEquals("Async started", true, request.isAsyncStarted()); + assertTrue("Async not started", request.isAsyncStarted()); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java index cb26910d3d..6ca92806d9 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/result/ModelResultMatchersTests.java @@ -31,25 +31,21 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; - - /** - * Unit tests for - * {@link org.springframework.test.web.servlet.result.ModelResultMatchers}. + * Unit tests for {@link ModelResultMatchers}. * * @author Craig Walls + * @author Sam Brannen */ -public class ModelResultMatchersTests { - - private ModelResultMatchers matchers; +class ModelResultMatchersTests { + private final ModelResultMatchers matchers = new ModelResultMatchers(); private MvcResult mvcResult; private MvcResult mvcResultWithError; - @BeforeEach - public void setUp() throws Exception { - this.matchers = new ModelResultMatchers(); + @BeforeEach + void setUp() throws Exception { ModelAndView mav = new ModelAndView("view", "good", "good"); BindingResult bindingResult = new BeanPropertyBindingResult("good", "good"); mav.addObject(BindingResult.MODEL_KEY_PREFIX + "good", bindingResult); @@ -68,118 +64,130 @@ public class ModelResultMatchersTests { } @Test - public void attributeExists() throws Exception { + void attributeExists() throws Exception { this.matchers.attributeExists("good").match(this.mvcResult); } @Test - public void attributeExists_doesNotExist() throws Exception { + void attributeExists_doesNotExist() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeExists("bad").match(this.mvcResult)); } @Test - public void attributeDoesNotExist() throws Exception { + void attributeDoesNotExist() throws Exception { this.matchers.attributeDoesNotExist("bad").match(this.mvcResult); } @Test - public void attributeDoesNotExist_doesExist() throws Exception { + void attributeDoesNotExist_doesExist() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeDoesNotExist("good").match(this.mvcResultWithError)); } @Test - public void attribute_equal() throws Exception { + void attribute_equal() throws Exception { this.matchers.attribute("good", is("good")).match(this.mvcResult); } @Test - public void attribute_notEqual() throws Exception { + void attribute_notEqual() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attribute("good", is("bad")).match(this.mvcResult)); } @Test - public void hasNoErrors() throws Exception { + void hasNoErrors() throws Exception { this.matchers.hasNoErrors().match(this.mvcResult); } @Test - public void hasNoErrors_withErrors() throws Exception { + void hasNoErrors_withErrors() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.hasNoErrors().match(this.mvcResultWithError)); } @Test - public void attributeHasErrors() throws Exception { + void attributeHasErrors() throws Exception { this.matchers.attributeHasErrors("date").match(this.mvcResultWithError); } @Test - public void attributeHasErrors_withoutErrors() throws Exception { + void attributeErrorCount() throws Exception { + this.matchers.attributeErrorCount("date", 1).match(this.mvcResultWithError); + } + + @Test + void attributeErrorCount_withWrongErrorCount() throws Exception { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> this.matchers.attributeErrorCount("date", 2).match(this.mvcResultWithError)) + .withMessage("Binding/validation error count for attribute 'date', expected:<2> but was:<1>"); + } + + @Test + void attributeHasErrors_withoutErrors() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasErrors("good").match(this.mvcResultWithError)); } @Test - public void attributeHasNoErrors() throws Exception { + void attributeHasNoErrors() throws Exception { this.matchers.attributeHasNoErrors("good").match(this.mvcResult); } @Test - public void attributeHasNoErrors_withoutAttribute() throws Exception { + void attributeHasNoErrors_withoutAttribute() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasNoErrors("missing").match(this.mvcResultWithError)); } @Test - public void attributeHasNoErrors_withErrors() throws Exception { + void attributeHasNoErrors_withErrors() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasNoErrors("date").match(this.mvcResultWithError)); } @Test - public void attributeHasFieldErrors() throws Exception { + void attributeHasFieldErrors() throws Exception { this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResultWithError); } @Test - public void attributeHasFieldErrors_withoutAttribute() throws Exception { + void attributeHasFieldErrors_withoutAttribute() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasFieldErrors("missing", "bad").match(this.mvcResult)); } @Test - public void attributeHasFieldErrors_withoutErrorsForAttribute() throws Exception { + void attributeHasFieldErrors_withoutErrorsForAttribute() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResult)); } @Test - public void attributeHasFieldErrors_withoutErrorsForField() throws Exception { + void attributeHasFieldErrors_withoutErrorsForField() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasFieldErrors("date", "good", "time").match(this.mvcResultWithError)); } @Test - public void attributeHasFieldErrorCode() throws Exception { + void attributeHasFieldErrorCode() throws Exception { this.matchers.attributeHasFieldErrorCode("date", "time", "error").match(this.mvcResultWithError); } @Test - public void attributeHasFieldErrorCode_withoutErrorOnField() throws Exception { + void attributeHasFieldErrorCode_withoutErrorOnField() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasFieldErrorCode("date", "time", "incorrectError").match(this.mvcResultWithError)); } @Test - public void attributeHasFieldErrorCode_startsWith() throws Exception { + void attributeHasFieldErrorCode_startsWith() throws Exception { this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("err")).match(this.mvcResultWithError); } @Test - public void attributeHasFieldErrorCode_startsWith_withoutErrorOnField() throws Exception { + void attributeHasFieldErrorCode_startsWith_withoutErrorOnField() throws Exception { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.matchers.attributeHasFieldErrorCode("date", "time", startsWith("inc")).match(this.mvcResultWithError)); } @@ -187,4 +195,5 @@ public class ModelResultMatchersTests { private MvcResult getMvcResult(ModelAndView modelAndView) { return new StubMvcResult(null, null, null, null, modelAndView, null, null); } + } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java index a96a38e5b0..e96c0c1f6c 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java @@ -52,6 +52,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder 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.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** @@ -93,6 +94,7 @@ public class JavaConfigTests { this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()) + .andExpect(request().asyncNotStarted()) .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}")); } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java index fd864e7573..65d8be3be9 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java @@ -41,6 +41,7 @@ import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -68,6 +69,7 @@ public class AsyncTests { public void callable() throws Exception { MvcResult mvcResult = this.mockMvc.perform(get("/1").param("callable", "true")) .andExpect(request().asyncStarted()) + .andExpect(request().asyncResult(equalTo(new Person("Joe")))) .andExpect(request().asyncResult(new Person("Joe"))) .andReturn(); diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/FlashAttributeAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/FlashAttributeAssertionTests.java index 8a439e87ff..89466b75df 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/FlashAttributeAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/FlashAttributeAssertionTests.java @@ -18,15 +18,14 @@ package org.springframework.test.web.servlet.samples.standalone.resultmatchers; import java.net.URL; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; 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.RequestMethod; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -40,55 +39,59 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standal * Examples of expectations on flash attributes. * * @author Rossen Stoyanchev + * @author Sam Brannen */ -public class FlashAttributeAssertionTests { +class FlashAttributeAssertionTests { - private MockMvc mockMvc; + private final MockMvc mockMvc = standaloneSetup(new PersonController()) + .alwaysExpect(status().isFound()) + .alwaysExpect(flash().attributeCount(3)) + .build(); - @BeforeEach - public void setup() { - this.mockMvc = standaloneSetup(new PersonController()) - .alwaysExpect(status().isFound()) - .alwaysExpect(flash().attributeCount(3)) - .build(); + @Test + void attributeCountWithWrongCount() throws Exception { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> this.mockMvc.perform(post("/persons")).andExpect(flash().attributeCount(1))) + .withMessage("FlashMap size expected:<1> but was:<3>"); } @Test - public void testExists() throws Exception { + void attributeExists() throws Exception { this.mockMvc.perform(post("/persons")) .andExpect(flash().attributeExists("one", "two", "three")); } @Test - public void testEqualTo() throws Exception { + void attributeEqualTo() throws Exception { this.mockMvc.perform(post("/persons")) .andExpect(flash().attribute("one", "1")) .andExpect(flash().attribute("two", 2.222)) - .andExpect(flash().attribute("three", new URL("https://example.com"))) - .andExpect(flash().attribute("one", equalTo("1"))) // Hamcrest... - .andExpect(flash().attribute("two", equalTo(2.222))) - .andExpect(flash().attribute("three", equalTo(new URL("https://example.com")))); + .andExpect(flash().attribute("three", new URL("https://example.com"))); } @Test - public void testMatchers() throws Exception { + void attributeMatchers() throws Exception { this.mockMvc.perform(post("/persons")) .andExpect(flash().attribute("one", containsString("1"))) .andExpect(flash().attribute("two", closeTo(2, 0.5))) - .andExpect(flash().attribute("three", notNullValue())); + .andExpect(flash().attribute("three", notNullValue())) + .andExpect(flash().attribute("one", equalTo("1"))) + .andExpect(flash().attribute("two", equalTo(2.222))) + .andExpect(flash().attribute("three", equalTo(new URL("https://example.com")))); } @Controller private static class PersonController { - @RequestMapping(value="/persons", method=RequestMethod.POST) - public String save(RedirectAttributes redirectAttrs) throws Exception { + @PostMapping("/persons") + String save(RedirectAttributes redirectAttrs) throws Exception { redirectAttrs.addFlashAttribute("one", "1"); redirectAttrs.addFlashAttribute("two", 2.222); redirectAttrs.addFlashAttribute("three", new URL("https://example.com")); return "redirect:/person/1"; } } + } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ModelAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ModelAssertionTests.java index 49e86bb308..6856253c3a 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ModelAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ModelAssertionTests.java @@ -49,14 +49,13 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standal * * @author Rossen Stoyanchev */ -public class ModelAssertionTests { +class ModelAssertionTests { private MockMvc mockMvc; @BeforeEach - public void setup() { - + void setup() { SampleController controller = new SampleController("a string value", 3, new Person("a name")); this.mockMvc = standaloneSetup(controller) @@ -67,7 +66,7 @@ public class ModelAssertionTests { } @Test - public void testAttributeEqualTo() throws Exception { + void attributeEqualTo() throws Exception { mockMvc.perform(get("/")) .andExpect(model().attribute("integer", 3)) .andExpect(model().attribute("string", "a string value")) @@ -77,7 +76,7 @@ public class ModelAssertionTests { } @Test - public void testAttributeExists() throws Exception { + void attributeExists() throws Exception { mockMvc.perform(get("/")) .andExpect(model().attributeExists("integer", "string", "person")) .andExpect(model().attribute("integer", notNullValue())) // Hamcrest... @@ -85,7 +84,7 @@ public class ModelAssertionTests { } @Test - public void testAttributeHamcrestMatchers() throws Exception { + void attributeHamcrestMatchers() throws Exception { mockMvc.perform(get("/")) .andExpect(model().attribute("integer", equalTo(3))) .andExpect(model().attribute("string", allOf(startsWith("a string"), endsWith("value")))) @@ -93,12 +92,12 @@ public class ModelAssertionTests { } @Test - public void testHasErrors() throws Exception { + void hasErrors() throws Exception { mockMvc.perform(post("/persons")).andExpect(model().attributeHasErrors("person")); } @Test - public void testHasNoErrors() throws Exception { + void hasNoErrors() throws Exception { mockMvc.perform(get("/")).andExpect(model().hasNoErrors()); } @@ -108,12 +107,12 @@ public class ModelAssertionTests { private final Object[] values; - public SampleController(Object... values) { + SampleController(Object... values) { this.values = values; } @RequestMapping("/") - public String handle(Model model) { + String handle(Model model) { for (Object value : this.values) { model.addAttribute(value); } @@ -121,7 +120,7 @@ public class ModelAssertionTests { } @PostMapping("/persons") - public String create(@Valid Person person, BindingResult result, Model model) { + String create(@Valid Person person, BindingResult result, Model model) { return "view"; } } @@ -130,7 +129,7 @@ public class ModelAssertionTests { private static class ModelAttributeAdvice { @ModelAttribute("globalAttrName") - public String getAttribute() { + String getAttribute() { return "Global Attribute Value"; } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/RequestAttributeAssertionTests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/RequestAttributeAssertionTests.java index 562af455fa..37efd72414 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/RequestAttributeAssertionTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/RequestAttributeAssertionTests.java @@ -16,7 +16,6 @@ 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; @@ -37,40 +36,37 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standal * * @author Rossen Stoyanchev */ -public class RequestAttributeAssertionTests { +class RequestAttributeAssertionTests { - private MockMvc mockMvc; + private final MockMvc mockMvc = standaloneSetup(new SimpleController()).build(); - @BeforeEach - public void setup() { - this.mockMvc = standaloneSetup(new SimpleController()).build(); - } @Test - public void testRequestAttributeEqualTo() throws Exception { + void requestAttributeEqualTo() throws Exception { this.mockMvc.perform(get("/main/1").servletPath("/main")) .andExpect(request().attribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/{id}")) - .andExpect(request().attribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/1")) - .andExpect(request().attribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, equalTo("/{id}"))) - .andExpect(request().attribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, equalTo("/1"))); + .andExpect(request().attribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/1")); } @Test - public void testRequestAttributeMatcher() throws Exception { - + void requestAttributeMatcher() throws Exception { String producibleMediaTypes = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE; this.mockMvc.perform(get("/1")) .andExpect(request().attribute(producibleMediaTypes, hasItem(MediaType.APPLICATION_JSON))) .andExpect(request().attribute(producibleMediaTypes, not(hasItem(MediaType.APPLICATION_XML)))); + + this.mockMvc.perform(get("/main/1").servletPath("/main")) + .andExpect(request().attribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, equalTo("/{id}"))) + .andExpect(request().attribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, equalTo("/1"))); } @Controller private static class SimpleController { - @RequestMapping(value="/{id}", produces="application/json") - public String show() { + @RequestMapping(path="/{id}", produces="application/json") + String show() { return "view"; } } 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 e72288fb59..508c9f6372 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 @@ -18,7 +18,6 @@ package org.springframework.test.web.servlet.samples.standalone.resultmatchers; import java.util.Locale; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.stereotype.Controller; @@ -30,7 +29,9 @@ import org.springframework.web.bind.annotation.SessionAttributes; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -40,34 +41,44 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standal * Examples of expectations on created session attributes. * * @author Rossen Stoyanchev + * @author Sam Brannen */ -public class SessionAttributeAssertionTests { +class SessionAttributeAssertionTests { - private MockMvc mockMvc; + private final MockMvc mockMvc = standaloneSetup(new SimpleController()) + .defaultRequest(get("/")) + .alwaysExpect(status().isOk()) + .build(); - @BeforeEach - public void setup() { - this.mockMvc = standaloneSetup(new SimpleController()) - .defaultRequest(get("/")) - .alwaysExpect(status().isOk()) - .build(); + + @Test + void sessionAttributeEqualTo() throws Exception { + this.mockMvc.perform(get("/")) + .andExpect(request().sessionAttribute("locale", Locale.UK)); + + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> + this.mockMvc.perform(get("/")) + .andExpect(request().sessionAttribute("locale", Locale.US))) + .withMessage("Session attribute 'locale' expected: but was:"); } @Test - public void testSessionAttributeEqualTo() throws Exception { + void sessionAttributeMatcher() throws Exception { this.mockMvc.perform(get("/")) - .andExpect(request().sessionAttribute("locale", Locale.UK)) + .andExpect(request().sessionAttribute("bogus", is(nullValue()))) + .andExpect(request().sessionAttribute("locale", is(notNullValue()))) .andExpect(request().sessionAttribute("locale", equalTo(Locale.UK))); + + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> + this.mockMvc.perform(get("/")) + .andExpect(request().sessionAttribute("bogus", is(notNullValue())))) + .withMessageContaining("null"); } @Test - public void testSessionAttributeMatcher() throws Exception { - this.mockMvc.perform(get("/")) - .andExpect(request().sessionAttribute("locale", notNullValue())); - } - - @Test - public void testSessionAttributeDoesNotExist() throws Exception { + void sessionAttributeDoesNotExist() throws Exception { this.mockMvc.perform(get("/")) .andExpect(request().sessionAttributeDoesNotExist("bogus", "enigma")); @@ -84,12 +95,12 @@ public class SessionAttributeAssertionTests { private static class SimpleController { @ModelAttribute - public void populate(Model model) { + void populate(Model model) { model.addAttribute("locale", Locale.UK); } @RequestMapping("/") - public String handle() { + String handle() { return "view"; } }