2016-11-20 41 views
0

我必須測試這個;如何在spring-mvc-test中傳入參數?

/** 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")); 
} 

我真的不明白我怎麼能通過這個Principal實例。 我該怎麼做?

回答

0

最簡單方法是做

@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

+0

此代碼不會有絲毫的工作 – Mattia