0

I have to test this;

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

my test looks like that;

@Test
public void getProfileBalance() throws Exception {
    this.mockMvc.perform(get("/profile/balance")
            .andExpect(status().isOk())
            .andExpect(view().name("balance"));
} 

I really don't understand how I could pass in that Principal instance. How can I do that?

Mattia
  • 179
  • 15

1 Answers1

0

Easiest way is by doing

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

Or you can use the Spring Security Test library

shazin
  • 21,379
  • 3
  • 54
  • 71