"Cannot resolve method" with mockito
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
![Krzysztof Majewski](https://i.stack.imgur.com/KlOcy.png?s=256&g=1)
Krzysztof Majewski
Java Developer with over 5 years of experience. Looking for remote work opportunities My GitHub: https://github.com/MajewskiKrzysztof LinkedIn: https://www.linkedin.com/in/majewski-krzysztof
Updated on July 09, 2022Comments
-
Krzysztof Majewski almost 2 years
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 extendsGrantedAuthority
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
andthenReturn()
method from it is:OngoingStubbing<T> thenReturn(T value);
What is the problem?
-
Mahsa over 2 yearslovely trick! it has solved a couple of other errors on my tests as well! thank you!