简体   繁体   中英

JUnit 5 Spring Security WebMvcTest no bean of type PasswordEncoder

I'm trying to test a basic Page Controller which returns a thymeleaf template. The controller looks like this:

@Controller
public class EntryOverviewController {

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

        return ApplicationConstants.VIEW_ENTRY_OVERVIEW;
    }

my WebSecurityConfig looks like this:

@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();
    }
}

My test looks like this:

@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));
    }

}

Now when I want to execute my junit 5 test, it fails with the error message 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)}

When I mock the passwordEncoder with @MockBean it gives the error password cannot be null.

Instead of autowiring the PasswordEncoder just use passwordEncoder(). See inter-bean dependencies here https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/beans.html#beans-java-configuration-annotation .

Is there a reason you want to name the encoder bean? You do not have multiple implementations of passwordEncoder.

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

I think spring has a problem while mocking this implementation. Rather, you could just have

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

and it should work.

I solved it by simple changing the class annotation.

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

so I added the @Import statement and it worked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM