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!

上一篇:Mockito不能mock final类的解决办法


下一篇:Maven测试项目中,如何根据不同的JUnit版本,配置pom.xml文件以使用PowerMock的Mockito扩展