我正在使用EasyMock(3.2)。我想为基于Spring Security的部分安全系统编写测试。我想模拟 Authentication
,以便它返回授权的空列表。其方法声明如下:
Collection<? extends GrantedAuthority> getAuthorities();
所以我写了一个测试:
Authentication authentication = createMock(Authentication.class);
Collection<? extends GrantedAuthority> authorities = Collections.emptyList();
expect(authentication.getAuthorities()).andReturn(authorities);
但是编译器抱怨
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();
如建议的那样,它仍然无法编译,但是错误有些不同:
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
实际上是相同的。 最佳答案
从集合声明中删除项目类型,您会收到警告,但测试仍然有效。
@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);
}