2017-03-16 48 views
0

這是控制器:單元測試HttpSessionRequiredException:預期會話屬性

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

由於控制器需要一個會話屬性 「名」,因此,上述試驗拋出:

org.springframework.web.HttpSessionRequiredException: Expected session attribute 'name' 

如何測試需要會話屬性的控制器方法? 謝謝。

回答