Issue
I have to write a test function for findInContextUser based on JUnit Mock in Spring Boot but I have no idea how to write it.
How can I write findInContextUser for Junit Test?
Here are my code defined in UserService shown below.
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();
}
Here is my test class shown below.
@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();
}
Here is the error message shown below.
com.example.lib.exception.GenericException
Debug Part : 401 UNAUTHORIZED
I also added @WithMockUser(username = "username", password = "password", roles = "USER")
but nothing changed.
Solution
Here is the solution shown below.
Add this line shown below underneath when
parts
SecurityContextHolder.setContext(securityContext);
Answered By - S.N
Answer Checked By - Katrina (JavaFixing Volunteer)