1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
18
19 import java.net.URL;
20
21 import org.junit.Before;
22 import org.junit.Test;
23
24 import org.springframework.stereotype.Controller;
25 import org.springframework.test.web.servlet.MockMvc;
26 import org.springframework.web.bind.annotation.RequestMapping;
27 import org.springframework.web.bind.annotation.RequestMethod;
28 import org.springframework.web.servlet.mvc.support.RedirectAttributes;
29
30 import static org.hamcrest.Matchers.*;
31 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
32 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
33 import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
34
35
36
37
38
39
40 public class FlashAttributeAssertionTests {
41
42 private MockMvc mockMvc;
43
44
45 @Before
46 public void setup() {
47 this.mockMvc = standaloneSetup(new PersonController())
48 .alwaysExpect(status().isFound())
49 .alwaysExpect(flash().attributeCount(3))
50 .build();
51 }
52
53 @Test
54 public void testExists() throws Exception {
55 this.mockMvc.perform(post("/persons"))
56 .andExpect(flash().attributeExists("one", "two", "three"));
57 }
58
59 @Test
60 public void testEqualTo() throws Exception {
61 this.mockMvc.perform(post("/persons"))
62 .andExpect(flash().attribute("one", "1"))
63 .andExpect(flash().attribute("two", 2.222))
64 .andExpect(flash().attribute("three", new URL("http://example.com")))
65 .andExpect(flash().attribute("one", equalTo("1")))
66 .andExpect(flash().attribute("two", equalTo(2.222)))
67 .andExpect(flash().attribute("three", equalTo(new URL("http://example.com"))));
68 }
69
70 @Test
71 public void testMatchers() throws Exception {
72 this.mockMvc.perform(post("/persons"))
73 .andExpect(flash().attribute("one", containsString("1")))
74 .andExpect(flash().attribute("two", closeTo(2, 0.5)))
75 .andExpect(flash().attribute("three", notNullValue()));
76 }
77
78
79 @Controller
80 private static class PersonController {
81
82 @RequestMapping(value="/persons", method=RequestMethod.POST)
83 public String save(RedirectAttributes redirectAttrs) throws Exception {
84 redirectAttrs.addFlashAttribute("one", "1");
85 redirectAttrs.addFlashAttribute("two", 2.222);
86 redirectAttrs.addFlashAttribute("three", new URL("http://example.com"));
87 return "redirect:/person/1";
88 }
89 }
90 }