I'm using Spring security and would like to unit test the password returned by my service. However, as this is encrypted, I'm trying to mock the method that does this encription which is inside the class which extends from WebSecurityConfigurerAdapter.
@Override
public void configure(AuthenticationManagerBuilder auth){
auth.userDetailsService(userDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
}
So I'm trying something like this
@Autowired
AuthenticationManagerBuilder auth;
static class PasswordEncoderTest implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return charSequence.toString().equals(s);
}
}
@Test
void testCreateUser() throws Exception {
UserCreateDto userCreateDto = new UserCreateDto("user", "test", "user@gmail.com", "user@gmail.com", "123456", "basic");
User userMocked = new User(userId, "user", "test", "user@gmail.com", "user@gmail.com", "123456", "basic");
PasswordEncoderTest passwordEncoderTest = new PasswordEncoderTest();
passwordEncoderTest.encode("123456");
when(auth.userDetailsService(myUserDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance())).thenReturn(auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoderTest));
userCreateDto = userCommandService.createUser(userCreateDto);
assertEquals(userMocked.getPassword(), userCreateDto.getPassword());
}
But it fails with DaoAuthenticationConfigurer cannot be returned by generateToken() generateToken() should return String
Not sure if the approach is correct and if it is what I may be doing wrong.
Thank you.
UPDATE
https://github.com/francislainy/adverts-backend/tree/dev_jwt
Based on my conversation with Plalx, It seems I should be injecting password encoder rather than bycript and have different configurations between the main and test classes. Will try that and get back here with further updates.