unit test HttpSessionRequiredException:预期的会话属性

时间:2017-03-16 01:32:13

标签: spring-boot

这是控制器:

@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'

如何测试需要会话属性的控制器方法? 感谢。

1 个答案:

答案 0 :(得分:0)

MockMvc有一种设置会话属性的方法。

Session attributes