因此,我添加了功能以允许用户仅更改自己的个人资料信息,但我在添加该逻辑进行测试时遇到问题。
这是我的服务和功能,我检查发送请求的用户是否正在尝试更新自己的详细信息。
public ApplicantDetailsResponseDTO updateByUserID(Integer id, ApplicantDetailsRequestDTO newApplicantDetails) {
ApplicantDetails applicantDetails = applicantDetailsRepository.findByUserId(id)
.orElseThrow(() -> new EntityNotFoundException("Details of applicant with ID " + id + " not found"));
if(!isAuthorizedForChange(applicantDetails.getUser().getUsername())) {
return null;
}
applicantDetails.setFirstname(newApplicantDetails.getFirstname());
applicantDetails.setLastname(newApplicantDetails.getLastname());
applicantDetails.setPhoneNumber(newApplicantDetails.getPhoneNumber());
ApplicantDetails updatedApplicantDetails = applicantDetailsRepository.save(applicantDetails);
return applicantDetailsMapper.mapToApplicantDetailsResponseDTO(updatedApplicantDetails);
}
public boolean isAuthorizedForChange(String username) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails currentUser = (UserDetails) authentication.getPrincipal();
return Objects.equals(username, currentUser.getUsername());
}
这是我的测试设置
@InjectMocks
private ApplicantDetailsService applicantDetailsService;
@Mock
private ApplicantDetailsRepository applicantDetailsRepository;
@Mock
private ApplicantDetailsMapper applicantDetailsMapper;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
这是我尝试模拟 isAuthorizedForChange 并返回 true
Mockito.when(applicantDetailsService.isAuthorizedForChange("username")).thenReturn(true);
问题是当我到达 isAuthorizedForChange 并收到此错误时,该函数仍在尝试运行:
java.lang.NullPointerException:无法调用“org.springframework.security.core.Authentication.getPrincipal()”,因为“authentication”为空
有没有一种方法可以在调用 isAuthorizedForChange 时返回 true,然后我将创建 2 个测试用例,分别用于判断其 true 和 false 的情况并测试行为。
我认为您的 SecurityHolder 没有任何上下文和身份验证。所以我们需要为其模拟数据。
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Authentication authentication = new UsernamePasswordAuthenticationToken("username", "password");
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);