我试图在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");
}
但我总是得到NullPointerException,即使我的身份验证是AnonymousAuthenticationToken的实例,测试总是return 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
!