Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot resolve method" with mockito

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?

like image 906
Krzysztof Majewski Avatar asked Jul 04 '18 07:07

Krzysztof Majewski


2 Answers

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

like image 64
Joe W Avatar answered Oct 22 '22 22:10

Joe W


If you want to ensure type safety you can initialize your collection as

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

Then you can normally use when(authentication.getAuthorities()).thenReturn(grantedAuthorities);

The advantage with this solution is that grantedAuthorities's type is preserved.

For more details check this article.

like image 2
voutsasg Avatar answered Oct 23 '22 00:10

voutsasg