Polish MockMvc result matchers and tests

This commit is contained in:
Sam Brannen
2019-10-23 14:03:44 +02:00
parent 82f64f6a8d
commit eabf357640
13 changed files with 176 additions and 126 deletions

View File

@@ -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);
}
}

View File

@@ -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}"));
}

View File

@@ -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();

View File

@@ -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";
}
}
}

View File

@@ -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";
}
}

View File

@@ -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";
}
}

View File

@@ -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:<en_US> but was:<en_GB>");
}
@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";
}
}