mockito 如何在JUnit中模拟Spring Security

dtcbnfnu  于 2023-03-12  发布在  Spring
关注(0)|答案(1)|浏览(271)

我在JUnit中模拟有关Spring Security的某些部分时遇到了问题。
我试着写一个关于用户注册的服务测试,但是我不能处理模拟部分。
下面是register方法中的相关部分

@Service
@Transactional
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final AuthenticationManager authenticationManager;

    private final JwtTokenProvider jwtTokenProvider;

    private final UserRepository userRepository;

    private final PasswordEncoder passwordEncoder;

    public AuthResponse register(RegisterRequest registerRequest) {
    ...

    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(registerRequest.getUsername(), registerRequest.getPassword());
    Authentication auth = authenticationManager.authenticate(authToken);
    SecurityContextHolder.getContext().setAuthentication(auth);
    String jwtToken = jwtTokenProvider.generateJwtToken(auth);
    ...
}

此处为试验方法相关部分

@Mock
    private UserRepository userRepository;
    
    @Mock
    private JwtTokenProvider jwtTokenProvider;
    
    @Mock
    private AuthenticationManager authenticationManager;
    
    @InjectMocks
    private AuthServiceImpl authService;
    
    @Mock
    private PasswordEncoder passwordEncoder;
    
    @Mock
    private SecurityContext securityContext;

    @Mock
    private Authentication authentication;

    @Test
    public void shouldRegister() {

    // when
    when(userRepository.save(any(User.class))).thenReturn(user);
            
    when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
                    .thenReturn(new UsernamePasswordAuthenticationToken(registerRequest.getUsername(), registerRequest.getPassword()));
            when(SecurityContextHolder.getContext()).thenReturn(securityContext);
    when(securityContext.getAuthentication()).thenReturn(authentication);
            
when(jwtTokenProvider.generateJwtToken(any(Authentication.class))).thenReturn("test_token");
}

这是下面显示的问题。

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

下面是pom.xml中定义的Spring安全测试依赖项

<dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-test</artifactId>
     <scope>test</scope>
</dependency>
gfttwv5a

gfttwv5a1#

例外情况是,您不是在嘲笑mock。SecurityContextHolder.getContext().getAuthentication()不是mock,mockito无法嘲笑它的行为。
@DhavalGajjar为您提供了一个答案,它将帮助您创建一个针对Spring Security的测试。Mockito将很难为Spring Security工作,这就是为什么有一个spring-security-test模块可用于帮助创建它,示例在@DhavalGajjar的链接中

相关问题