我必须对此进行测试;
/** Displays the balance us page. */
@RequestMapping(value = "/profile/balance")
public ModelAndView balance(Principal principal) {
ModelAndView model = new ModelAndView("balance");
String username = principal.getName();
User user = userService.findUserByUsername(username);
model.addObject("moneyEarned", user.getMoneyEarned());
model.addObject("moneySpent", user.getMoneySpent());
return model;
}我的测试是这样的;
@Test
public void getProfileBalance() throws Exception {
this.mockMvc.perform(get("/profile/balance")
.andExpect(status().isOk())
.andExpect(view().name("balance"));
} 我真的不明白我怎么能传入这个主体实例。我该怎么做呢?
发布于 2016-11-21 01:52:25
最简单的方法就是做
@Test
public void getProfileBalance() throws Exception {
SecurityContext ctx = new SecurityContextImpl();
ctx.setAuthentication(new UsernamePasswordAuthenticationToken("principal", "password"));
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
SecurityContextHolder.setContext(ctx);
this.mockMvc.perform(get("/profile/balance")
.andExpect(status().isOk())
.andExpect(view().name("balance"));
SecurityContextHolder.clearContext();
} 或者,您可以使用Spring Security Test library
https://stackoverflow.com/questions/40707237
复制相似问题