我尝试在 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,测试总是转到 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
!
关于java - 模拟 Spring 安全类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54659999/