使用userDetailsService的spring安全测试在测试用例中给出了非法状态异常



我有一些弹簧控制器测试以前工作正常。 我最近使用userDetailsService添加了身份验证,现在当我运行控制器测试时,它说:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'nl.kars.lms.service.MyUserDetailsService' available: 
expected at least 1 bean which qualifies as autowire candidate.

我不明白为什么,因为一切都应该正确配置。它仅在运行控制器测试时发生,运行应用程序工作正常。这是我的课程。

测试用例

@RunWith(SpringRunner.class)
@WebMvcTest(ActionController.class)
public class ActionControllerTests {
@Autowired
private MockMvc mvc;
@MockBean
private ActionService service;
@Test
public void testGetActions_returns_result_from_service() throws Exception {
int actionId = 1;
Action action = new Action();
action.setId(actionId);
List<Action> actionsList = Arrays.asList(action);
given(service.getActions()).willReturn(actionsList);
mvc.perform(get("/actions")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].id", Matchers.is(actionId)));
}
}

配置

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
MyUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
http.csrf().disable()
.authorizeRequests()
.antMatchers("/**")
.fullyAuthenticated()
.and().httpBasic();
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}

用户详细信息服务

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private EmployeeService employeeService;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return new EmployeeDetails(employeeService.getEmployeeByEmail(email));
}
}

我的问题是,如何阻止错误发生?我做错了什么?在这一点上,我迷茫了。 谢谢

由于您在@Service("userDetailsService")中将MyUserDetailsService命名为userDetailsService,因此您有两个选择

第一种:
在安全配置中使用@Qualifier("userDetailsService")

第二种选择:
在安全配置中自动连线UserDetailsService而不是MyUserDetailsService

我建议您尝试第一种选择

@Autowired
@Qualifier("userDetailsService")
MyUserDetailsService userDetailsService;

相关内容

最新更新