如何使用通配符模拟泛型方法的行为

fra*_*acz 3 java generics easymock

我正在使用EasyMock(3.2).我想基于Spring Security为我的部分安全系统编写一个测试.我想嘲笑Authentication它,以便它返回空的权限列表.其方法声明如下:

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

所以我写了一个测试:

Authentication authentication = createMock(Authentication.class);
Collection<? extends GrantedAuthority> authorities = Collections.emptyList();
expect(authentication.getAuthorities()).andReturn(authorities);
Run Code Online (Sandbox Code Playgroud)

但是编译器正在抱怨第三条线路andReturn:

The method andReturn(Collection<capture#1-of ? extends GrantedAuthority>) in the type IExpectationSetters<Collection<capture#1-of ? extends GrantedAuthority>> is not applicable for the arguments (Collection<capture#2-of ? extends GrantedAuthority>

我究竟做错了什么?


更新:

当我将声明更改authorities为:

Collection<GrantedAuthority> authorities = Collections.emptyList();
Run Code Online (Sandbox Code Playgroud)

如建议的那样,它仍然没有编译,但错误有点不同:

The method andReturn(Collection<capture#1-of ? extends GrantedAuthority>) in the type IExpectationSetters<Collection<capture#1-of ? extends GrantedAuthority>> is not applicable for the arguments (Collection<GrantedAuthority>)

我确保GrantedAuthority在两个声明中实际上是相同的 - org.springframework.security.core.GrantedAuthority.

die*_*sis 6

从集合声明中删除项目类型,您将收到警告,但测试将起作用.

@Test
public void testFoo()
    {
    // setup
    Authentication mockAuthentication = createMock(Authentication.class);
    Collection authorities = Collections.emptyList();
    expect(mockAuthentication.getAuthorities()).andReturn(authorities);

    // exercise
    EasyMock.replay(mockAuthentication);
    Collection<? extends GrantedAuthority> retAuth = mockAuthentication.getAuthorities();

    // verify
    EasyMock.verify(mockAuthentication);
    assertEquals(authorities, retAuth);
    }
Run Code Online (Sandbox Code Playgroud)