我有以下常数:
private static final Collection<? extends GrantedAuthority> USER_ROLES = ImmutableSet.of((GrantedAuthority)ROLE_ADMIN);
private static final Collection<? extends GrantedAuthority> CUSTOM_GROUPS = AuthorityUtils.commaSeparatedStringToAuthorityList("SOME_GROUP");
在测试中,我有以下嘲弄条件:
when(mapper.mapAuthorities(CUSTOM_GROUPS)).thenReturn(USER_ROLES);
Mapper在这种情况下是实现GrantedAuthoritiesMapper
spring接口的类,需要实现此方法:
Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities);
当我尝试执行此模拟条件时,我收到编译错误:
The method thenReturn(Collection<capture#2-of ? extends GrantedAuthority>) in the type OngoingStubbing<Collection<capture#2-of ? extends GrantedAuthority>> is not applicable for the arguments (Collection<capture#3-of ? extends GrantedAuthority>)
我可以修复它只是用这一个覆盖这个条件:
when(customGroupsMapper.mapAuthorities(CUSTOM_GROUPS)).thenReturn((Collection)USER_ROLES);
但实际上我不喜欢会出现的警告信息:Collection is a raw type. References to generic type Collection<E> should be parameterized
。
有人可以解释为什么会发生这种情况以及为什么mockito无法匹配相同的类型?是否有其他方法可以解决此类问题?
答案 0 :(得分:1)
不幸的是,这与Mockito无关,但Java处理泛型,即擦除。
我建议使用简单的工厂方法:
when(mapper.mapAuthorities(GROUP)).thenReturn(authorities(ROLE1, ROLE2));
@SuppressWarnings("unchecked")
private <T> ImmutableSet<T> authorities(GrantedAuthority... authorities) {
return (ImmutableSet<T>) ImmutableSet.copyOf(authorities);
}