我用Mockito测试我的控制器。 在控制器中测试我的方法:
@RequestMapping("/dispatcher")
public String disp(final HttpServletRequest request) {
if (request.isUserInRole("USER")) {
return "hello";
} else if (request.isUserInRole("ADMIN")) {
return "redirect:listUsers.htm";
}
throw new RuntimeException("This role is not registrated");
}
我的测试方法:
@Test
public void testDispatcher() throws Exception {
User user = userDao.findByLogin("log1");
TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(user, AuthorityUtils.createAuthorityList("USER"));
SecurityContextHolder.getContext().setAuthentication(testingAuthenticationToken);
System.out.println(testingAuthenticationToken);
mockMvc.perform(post("/dispatcher")
.principal(testingAuthenticationToken))
.andExpect(status().isOk());
}
错误: org.springframework.security.authentication.TestingAuthenticationToken@bf72b5bd:Principal:User [id = 1,firstName = name1,lastName = surname1,login = log1,email = email1 @ gmail.com,password = psw1,birthDate = 1980-01- 01 00:00:00.0,role = [id = 1,name = USER]];证书:[保护];认证:false;细节:null;没有授予任何权力
org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是java.lang.RuntimeException:此角色未注册
我如何设置方法request.isUserInRole(); 或者可能有我的问题的另一个解决方案
答案 0 :(得分:0)
通过添加GrandAuthorities更改我的测试,但isUserinRole也是" false"
validates :name, format: { with: /\A[a-zA-Z0-9\s]+\z/i, message: "can only contain letters and numbers." }