“Cannot resolve method” with mockito

主宰稳场 提交于 2020-12-04 15:57:06

问题


I use org.springframework.security.core.Authentication which has a method:

Collection<? extends GrantedAuthority> getAuthorities();

I want to mock it as below:

when(authentication.getAuthorities()).thenReturn(grantedAuthorities);

with authorities collection:

Collection<SimpleGrantedAuthority> grantedAuthorities = Lists.newArrayList(
        new SimpleGrantedAuthority(AuthoritiesConstants.USER));

And I am using org.springframework.security.core.authority.SimpleGrantedAuthority which extends GrantedAuthority

And Intellij gives me below compile error:

Cannot resolve method 'thenReturn(java.util.Collection<org.spring.security.core.authority.SimpleGrantedAuthority>)'

I use Mockito 2.15.0 and thenReturn() method from it is:

OngoingStubbing<T> thenReturn(T value);

What is the problem?


回答1:


Try using the other syntax to return your collection with a wildcard matching generic: doReturn(grantedAuthorities).when(authentication).getAuthorities();

This doReturn call isn't type-safe and results in a runtime check on type but for your purposes it will return the mocked list you want.

There are a lot of details using mockito and generics with wildcards. For more details: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#Wildcards



来源:https://stackoverflow.com/questions/51168430/cannot-resolve-method-with-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!