“无法解析方法”与嘲笑

Krz*_*ski 3 junit spring spring-security mockito

我使用org.springframework.security.core.Authentication其中的一种方法:

Collection<? extends GrantedAuthority> getAuthorities();
Run Code Online (Sandbox Code Playgroud)

我想模拟如下:

when(authentication.getAuthorities()).thenReturn(grantedAuthorities);
Run Code Online (Sandbox Code Playgroud)

与当局收集:

Collection<SimpleGrantedAuthority> grantedAuthorities = Lists.newArrayList(
        new SimpleGrantedAuthority(AuthoritiesConstants.USER));
Run Code Online (Sandbox Code Playgroud)

我正在使用org.springframework.security.core.authority.SimpleGrantedAuthority扩展GrantedAuthority

Intellij给了我下面的编译错误:

Cannot resolve method 'thenReturn(java.util.Collection<org.spring.security.core.authority.SimpleGrantedAuthority>)'
Run Code Online (Sandbox Code Playgroud)

我使用Mockito 2.15.0thenReturn()方法是:

OngoingStubbing<T> thenReturn(T value);
Run Code Online (Sandbox Code Playgroud)

问题是什么?

Joe*_*e W 6

尝试使用其他语法来返回带有通配符匹配的泛型的集合: doReturn(grantedAuthorities).when(authentication).getAuthorities();

doReturn调用不是类型安全的,并且会导致对类型的运行时检查,但是出于您的目的,它将返回您想要的模拟列表。

在通配符上使用嘲笑和泛型有很多细节。有关更多详细信息:http : //www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#Wildcards


vou*_*asg 5

如果您想确保类型安全,您可以将集合初始化为

 Collection grantedAuthorities =
 Lists.newArrayList(
         new SimpleGrantedAuthority(AuthoritiesConstants.USER));
Run Code Online (Sandbox Code Playgroud)

然后就可以正常使用了when(authentication.getAuthorities()).thenReturn(grantedAuthorities);

此解决方案的优点是grantedAuthorities保留了 的类型。

有关更多详细信息,请查看这篇文章