Spring Boot测试 - 没有限定Bean异常

时间:2018-02-01 16:56:51

标签: java spring spring-boot spring-test

在尝试使用Spring Boot框架进行一些测试时,我遇到了一个问题,即找到测试单元所依赖的Bean。

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authServerApplication': Unsatisfied dependency expressed through field 'passwordEncoder'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.crypto.password.PasswordEncoder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我的测试班:

    @RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest

public class UserDetailsTest {

    @Autowired
    private TestEntityManager entityManager;

//    @MockBean
//    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepo;

    @Test
    public void test() {
        OAuthUser user = null;
        this.entityManager.persist(new OAuthUser("Kelly", "Marchewa", "kmarchewa", "password"));
        user = userRepo.findByUserName("kmarchewa");
        System.out.println(user.getPassword());
        assertThat(user.getUserName()).isEqualTo("kmarchewa");


    }

}

如果我取消注释@MockBean部分,代码将编译正常。但是,我想测试存储库的密码编码和解码能力。根据我对the documentation的理解,@ SpringBootTest注释应该能够自动“拾取”@Configuration类。我有一个主@SpringBootApplication:

@SpringBootApplication
public class AuthServerApplication {

@Autowired
private PasswordEncoder passwordEncoder;

public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
}

@Bean
public CommandLineRunner demo(UserRepository repository) {
    return(args) -> {
        OAuthUser user = new OAuthUser();


        user.setFirstName("Kelly");
        user.setLastName("Marchewa");
        user.setPassword(passwordEncoder.encode("Admin"));
        user.setUserName("Admin");

    // repository.save(user);
    };
}
}

此Spring Boot应用程序依赖于其他三个@Configuration类:AppConfig,SecurityConfig和AuthServerConfig。对于此问题,SecurityConfig和AppConfig类是相关的(它们包括对PasswordEncoder bean的引用)。

AppConfig(部分)

@Configuration
public class AppConfig {

        @Value("${spring.datasource.url}")
        private String datasourceUrl;

        @Value("${spring.datasource.driverClassName}")
        private String dbDriverClassName;

        @Value("${spring.datasource.username}")
        private String dbUsername;

        @Value("${spring.datasource.password}")
        private String dbPassword;

        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
        /// more code here 
}

SecurityConfig:

    @Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private OAuthUserDetailsService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
}

    // Hash password
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
        .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http
               .sessionManagement()
               .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
               .and()
               .httpBasic()
               .realmName("test")
               .and()
               .csrf()
               .disable();

    }
}

UserRepository类非常简单:

    public interface UserRepository extends CrudRepository<OAuthUser, Long> {

    public OAuthUser findByUserName(String name);
}

如何确保为我的测试找到所有必需的bean? 感谢。

编辑:

如果我尝试在我的测试类中@Autowire bean,我会收到同样的错误。

@Autowired 
private PasswordEncoder passwordEncoder;

1 个答案:

答案 0 :(得分:1)

问题是@DataJpaTest这个注释应该仅用于数据存储库测试而不是完全集成(这是你正在做的事情),因为它只在上下文中创建持久性bean而不是所有的bean(原因豆无法找到)。您需要做的是仅使用@SpringBootTest并声明h2作为测试依赖项,这样就可以使用内存数据库创建应用程序的完整重新创建