I have a problem to mock some parts regarding Spring Security in JUnit.
I tried to write a service test regarding user registration but I couldn't handle with mock part.
Here is the relevant part in register method shown below
@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);
...
}
Here is the test method relevant part
@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");
}
Here is the issue shown below.
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);
Here is spring security test dependency defined in pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>