spring-security Sping Boot 服务测试的JUnit安全测试错误

wvyml7n5  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(165)

我必须在Sping 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"),但没有任何变化。

w1jd8yoj

w1jd8yoj1#

解决方案如下所示。
when部件下面添加下面所示的这一行

SecurityContextHolder.setContext(securityContext);

相关问题