这是控制器:
@Controller("person")
@SessionAttributes("name")
public class SomeController {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String save(@Valid Person person, Model model, @ModelAttribute("name") String name, BindingResult result) {}
}
这是测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PersonTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(username = "ram", authorities={"TEACHER"})
public void checkPersonInfoWhenNameMissingNameThenFailure() throws Exception {
MockHttpServletRequestBuilder createPerson = post("/person/add")
.param("aa", "bb");
mockMvc.perform(createPerson)
.andExpect(model().hasErrors());
}
}
因为控制器需要会话属性" name",所以上面的测试抛出:
org.springframework.web.HttpSessionRequiredException: Expected session attribute 'name'
如何测试需要会话属性的控制器方法? 感谢。