java-模拟Spring Security类

前端之家收集整理的这篇文章主要介绍了java-模拟Spring Security类 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图在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!

猜你在找的Java相关文章