java security类,java-模拟Spring Security类

在本文中,作者遇到了在测试UserServiceImpl类的getActualUser()方法时遇到的问题。当认证对象是AnonymousAuthenticationToken的实例时,测试抛出了NullPointerException。解决方案是缺少SecurityContextHolder.setContext()来设置模拟的SecurityContext。文章提供了测试类的代码片段,并指出这个遗漏导致了主要的NullPointerException。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

来源: https://codeday.me/bug/20191211/2106340.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值