【发布时间】:2022-10-24 19:02:58
【问题描述】:
我必须在 Spring Boot 中基于 JUnit Mock 为 findInContextUser 编写一个测试函数,但我不知道如何编写它。
如何为 Junit 测试编写 findInContextUser?
这是我在 UserService 中定义的代码,如下所示。
public UserDto getUserDto(String username) {
var user = findUserByUsername(username);
return UserDto.builder()
.id(user.getId())
.username(user.getUsername())
.role(user.getRole())
.build();
}
public UserDto findInContextUser() {
final Authentication authentication = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()).orElseThrow(notFoundUser(HttpStatus.UNAUTHORIZED));
final UserDetails details = Optional.ofNullable((UserDetails) authentication.getPrincipal()).orElseThrow(notFoundUser(HttpStatus.UNAUTHORIZED));
return getUserDto(details.getUsername());
}
private static Supplier<GenericException> notFoundUser(HttpStatus unauthorized) {
return () -> GenericException.builder().httpStatus(unauthorized).errorMessage("user not found!").build();
}
这是我的测试类,如下所示。
@Test
void itShouldFindInContextUser(){
// given - precondition or setup
User user = User.builder()
.username("username")
.password("password")
.role(Role.USER)
.build();
UserDto expected = UserDto.builder()
.id(user.getId())
.username(user.getUsername())
.role(user.getRole())
.build();
var roles = Stream.of(user.getRole())
.map(x -> new SimpleGrantedAuthority(x.name()))
.collect(Collectors.toList());
UserDetails details = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), roles);
Authentication authentication = Mockito.mock(Authentication.class);
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
// when - action or the behaviour that we are going test
when(securityContext.getAuthentication()).thenReturn(authentication);
when(securityContext.getAuthentication().getPrincipal()).thenReturn(details);
// then - verify the output
UserDto actual = userService.findInContextUser(); // ERROR IS HERE
assertEquals(expected, actual);
assertEquals(expected.getUsername(), actual.getUsername());
verify(userService, times(1)).findInContextUser();
}
这是如下所示的错误消息。
com.example.lib.exception.GenericException
Debug Part : 401 UNAUTHORIZED
我还添加了@WithMockUser(username = "username", password = "password", roles = "USER"),但没有任何改变。
【问题讨论】:
-
Spring Security @WithMockUser 注释可能会有所帮助。
-
@ILyaCyclone 使用
@WithMockUser后我仍然遇到同样的问题。我该如何解决? -
@ILyaCyclone 我仍然无法修复它。
标签: java spring-boot junit spring-security