【发布时间】:2016-09-28 08:34:49
【问题描述】:
我正在尝试在 Java 中模拟身份验证以进行身份验证。这是我模拟代码的测试类:
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(this.controller).build();
final List<AuthenticationProvider> providers = mock(ArrayList.class);
final AbstractUserDetailsAuthenticationProvider provider = mock(
AbstractUserDetailsAuthenticationProvider.class);
when(provider.supports(any(Class.class))).thenReturn(false);
when(providers.size()).thenReturn(1);
session = new MockHttpSession();
when(providers.get(anyInt())).thenReturn(provider);
when(request.getSession()).thenReturn(session);
when(request.getSession(false)).thenReturn(session);
when(providers.iterator()).thenReturn(new Iterator<AuthenticationProvider>() {
private int currentIndex = 0;
@Override
public AuthenticationProvider next() {
return providers.get(currentIndex++);
}
@Override
public boolean hasNext() {
return currentIndex < providers.size() && providers.get(currentIndex) != null;
}
});
SingleProviderAuthenticationManager manager = new SingleProviderAuthenticationManager(providers);
Map<String, AuthenticationManager> map = new HashMap<String, AuthenticationManager>();
map.put("db", manager);
filter.setAuthenticationManagerMap(map);
when(request.getMethod()).thenReturn("POST");
when(request.getParameter("username")).thenReturn("admin");
when(request.getParameter("password")).thenReturn("admin");
List<User> users = new ArrayList<User>();
User user = new User();
user.setSourceSystem("db");
users.add(user);
when(userService.getUserReferenceByUsername("admin")).thenReturn(users);
auth = filter.attemptAuthentication(request, response);
现在,在我将管理器放入 map.put() 方法的那一行,当我放入“db”时,它实际上将提供程序管理器提供为 null,而我在 ProviderManager 中得到了 NullPointerException。
for (AuthenticationProvider provider : getProviders()) {
if (!provider.supports(toTest)) {
continue;
}
即使我在我的主代码中使用提供程序测试了相同的东西,我通过它仍然显示NullPointerException。如果我输入“ldap”,它会在UsernamePasswordAuthenticationFilter 中给我一个NullPointerException:
(返回发生的最后一行)
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
我被困在这里,当我通过它们时,这两个东西根本不是null。有什么帮助吗?
【问题讨论】:
标签: java spring spring-mvc spring-security mockito