我试图在Java中模拟身份验证以进行身份验证。这是我用来模拟代码的测试类:
SELECT * FROM categories WHERE status = 1
现在,在我将管理器放入 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);
方法的行中,当我放置&#34; db&#34;它实际上会将提供者管理员设为map.put()
,我会在null
中获得NullPointerException
。
ProviderManager
即使我在主要代码中使用提供商测试了相同的内容,但仍然会显示 for (AuthenticationProvider provider : getProviders()) {
if (!provider.supports(toTest)) {
continue;
}
。如果我把&#34; ldap&#34;相反,它在NullPointerException
这里给了我NullPointerException
:
(返回的最后一行)
UsernamePasswordAuthenticationFilter
我被困在这里,当我通过它们时这两件事都不是 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);
}
。有什么帮助吗?
答案 0 :(得分:0)
不要模拟ArrayList而是创建新的数组列表并将其发送到实际的类,如下所示:
final List<AuthenticationProvider> providers = new ArrayList<>();
providers.add("AuthenticationProvider object values");
// when(providers.size())。thenReturn(1); - 如果你创建直接的arraylist对象,则无需执行此操作。
PS-如果您正在使用集合,请更喜欢创建新对象并将该对象发送到实际类而不是模拟和发送,这是最佳实践。
希望它有用。