我在與Java 8的Java應用程序的工作,使用流功能 我有這樣的POJO:Lambda表達式
public class Authority implements GrantedAuthority {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String authority;
public Authority(String authority) {
this.authority = authority;
}
@Override
public String getAuthority() {
return authority;
}
@Override
public String toString() {
return "Authority [authority=" + authority + "]";
}
}
和
public class User implements Serializable, UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
return authorities;
}
public boolean isAdmin() {
return getAuthorities().stream().filter
(o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
}
}
,我已經創建此Junit來檢查是否一切正常
@Test
public void isAdminTests() {
User adminUser = UserUtils.createBasicUser("[email protected]", "[email protected]", true);
Set<UserRole> adminUserRoles = new HashSet<>();
adminUserRoles.add(new UserRole(adminUser, new Role(RolesEnum.ADMIN)));
adminUser.getUserRoles().addAll(adminUserRoles);
System.out.print(adminUser.getAuthorities());
assertTrue (adminUser.isAdmin());
}
並且這是控制檯中的值:
[Authority [authority=ROLE_ADMIN]]
但是我有一個斷言錯誤
看起來像您的'isAdmin()'返回false。試過調試過嗎? – Shark
「Authority」類是怎麼樣的? –
'User'中的userRoles是什麼? –