我试图在UserServiceImpl类中为我的方法创建测试:
@Override
public User getActualUser() throws WebSecurityException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
return userRepository.findByLogin(authentication.getName());
}
throw new WebSecurityException("Authenticated user not found");
}
但是即使我的身份验证是AnonymousAuthenticationToken的实例,我也始终会得到NullPointerException,测试始终会返回userRepository.findByLogin(authentication.getName());线.
这是我的测试课:
@RunWith(MockitoJUnitRunner.class)
public class UserServiceImplTest {
@InjectMocks
UserServiceImpl userService;
@Mock
UserRepository userRepository;
@Test(expected = WebSecurityException.class)
public void testGetActualUserWhenAuthenticationIsInstanceOfAnonymousAuthenticationToken() {
//SETUP
SecurityContext securityContext = mock(SecurityContext.class);
Authentication authentication = mock(AnonymousAuthenticationToken.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
//CALL
userService.getActualUser();
}
@Test
public void testGetActualUserWhenAuthenticationIsNotInstanceOfAnonymousAuthenticationToken() {
//SETUP
User user = new User();
Authentication authentication = mock(Authentication.class);
when(userRepository.findByLogin(anyString())).thenReturn(user);
when(authentication.getName()).thenReturn("user");
//CALL
userService.getActualUser();
//TODO VERIFY
}
}
您可以为此方法创建适当的测试吗?
解决方法:
您忘记了:
SecurityContextHolder.setContext(/*mock*/securityContext);
在您的测试设置中,这将修复主要的NullPointerException!