簡體   English   中英

JUnit 5 Spring Security WebMvcTest 沒有 PasswordEncoder 類型的 bean

[英]JUnit 5 Spring Security WebMvcTest no bean of type PasswordEncoder

我正在嘗試測試一個返回 thymeleaf 模板的基本頁面控制器。 控制器看起來像這樣:

@Controller
public class EntryOverviewController {

    @GetMapping(ApplicationConstants.URL_ENTRY_OVERVIEW)
    public String getPage(Model model) {

        return ApplicationConstants.VIEW_ENTRY_OVERVIEW;
    }

我的 WebSecurityConfig 看起來像這樣:

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@Slf4j
@Configuration
@Order(1005)
public class WebSecurityConfig {

    @Configuration
    @Order(1005)
    public class WebAppSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http.authorizeRequests().antMatchers("/**").permitAll().and().headers().defaultsDisabled().cacheControl().and()
                    .httpStrictTransportSecurity().includeSubDomains(false).maxAgeInSeconds(31536000).and().frameOptions().disable().and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
        }
    }

    @Order(1004)
    @Configuration
    public static class ActuatorWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private PasswordEncoder passwordEncoder;

        @Value("${management.endpoints.web.access.user}")
        private String user;

        @Value("${management.endpoints.web.access.password}")
        private String password;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests().requestMatchers(EndpointRequest.to(HealthEndpoint.class))
                    .permitAll().anyRequest().authenticated().and().httpBasic().and().sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser(user).password(passwordEncoder.encode(password)).roles();
        }
    }

    /** Password encoder */
    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

我的測試是這樣的:

@ExtendWith(SpringExtension.class)
@WebMvcTest(EntryOverviewController.class)
class EntryOverviewControllerTest {

    @Autowired
    private MockMvc mvc;

    @WithMockUser(value = "user")
    @Test
    public void testCorrectModel() throws Exception {

      mvc.perform(get(ApplicationConstants.URL_ENTRY_OVERVIEW)).andExpect(status().isOk()).andExpect(model().attributeExists("registerEntry"))
                .andExpect(view().name(ApplicationConstants.VIEW_ENTRY_OVERVIEW));
    }

}

現在,當我想執行我的 junit 5 測試時,它失敗並顯示錯誤消息 org.springframework.beans.factory.NoSuchBeanDefinitionException: Noqualifying bean of type 'org.springframework.security.crypto.password.PasswordEncoder' available: expected at least 1 個有資格作為自動裝配候選者的 bean。 依賴注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

當我用@MockBean 模擬 passwordEncoder 時,它給出了錯誤密碼不能為空。

而不是自動裝配 PasswordEncoder 只需使用 passwordEncoder()。 在此處查看 bean 間的依賴關系https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/beans.html#beans-java-configuration-annotation

您是否有理由想要命名編碼器 bean? 您沒有 passwordEncoder 的多個實現。

@Bean(name = "passwordEncoder")
  public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
  }

我認為 spring 在嘲笑這個實現時有問題。 相反,你可以擁有

@Bean
  public PasswordEncoder passwordEncoder() {
   return new BCryptPasswordEncoder();
  }

它應該工作。

我通過簡單地更改類注釋來解決它。

@WebMvcTest(EntryOverviewController.class)
@Import(WebSecurityConfig.class)
class EntryOverviewControllerTest {
...
}

所以我添加了@Import 語句並且它起作用了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM