Я создаю новое приложение Spring Boot с нуля и хочу написать тесты для него.Я только что внедрил аутентификацию в свое приложение и хочу узнать, как работают роли.
Когда я использую свой UserRepository в процессе аутентификации, все работает как надо.Однако, когда я хочу использовать UserRepository в тестах, он говорит, что объект имеет значение null, то же самое, что нормально, когда я использую его в коде приложения.Это почему?Вот код.
Класс конфигурации безопасности:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private PowderizeUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.logout().permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManager) {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(passwordEncoder());
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationManager.authenticationProvider(authenticationProvider);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
Класс пользователя:
@Entity
@Table(name = "USERS")
@NoArgsConstructor
@Getter
public class User extends BaseEntity {
private String firstName;
private String lastName;
private String emailAddress;
private String nickname;
private String password;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
@ManyToMany(mappedBy = "users_roles")
private Set<Role> roles;
}
Репозиторий:
public interface UserRepository extends CrudRepository<User, Long> {
public Optional<User> findByEmailAddress(String email);
}
Класс реализации UserDetailsService,который использует хранилище без проблем:
@Service
public class PowderizeUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return new PowderizePrincipal(
userRepository.findByEmailAddress(email)
.orElseThrow(() -> new UsernameNotFoundException("User '" + email + "' not found."))
);
}
}
И тестовый класс, который возвращает NullPointerException:
@SpringBootTest
public class UsersAndRolesTest {
@Autowired
private UserRepository userRepository;
@Test
public void ww(){
assertThat(userRepository, notNullValue());
}
@Test
public void userExistsInDatabase(){
assertThat(userRepository.findByEmailAddress("admin@mail.com").isPresent(), notNullValue());
}
}
Я пытался использовать аннотации, такие как @Repository, @EnableJpaRepositories, фактически каждое решениеЯ обнаружил.IntelliJ также выделяет userRepository
с помощью «Не удалось автоматически подключить. Не найдены компоненты типа UserRepository».