Java 如何测试基于SpringSecurity表达式的访问控制。EL表达式找不到bean

Java 如何测试基于SpringSecurity表达式的访问控制。EL表达式找不到bean,java,spring,testing,spring-security,spring-el,Java,Spring,Testing,Spring Security,Spring El,我有一个使用Spring安全性的简单SpringBoot应用程序。 访问控制在运行时正常工作,但在测试时失败。 我发现以下错误: java.lang.IllegalArgumentException: Failed to evaluate expression '@userSecurity.hasUserId(authentication,#userId)' Caused by: org.springframework.expression.spel.SpelEvaluationExcepti

我有一个使用Spring安全性的简单SpringBoot应用程序。 访问控制在运行时正常工作,但在测试时失败。 我发现以下错误:

java.lang.IllegalArgumentException: Failed to evaluate expression '@userSecurity.hasUserId(authentication,#userId)'

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1058E: A problem occurred when trying to resolve bean 'userSecurity':'Could not resolve bean reference against BeanFactory'
它只是通过表达式检查Url中提供的用户ID是否与当前登录的用户匹配

...
  .antMatchers("/**/user/{userId}/**/")
                    .access("@userSecurity.hasUserId(authentication,#userId)")
...
创建了一个负责用户id值检查的bean:

@Component
public class UserSecurity {

    public boolean hasUserId(Authentication authentication, Long userId) {    
        Object principalRaw = authentication.getPrincipal();
        User loggedUser;
        if (principalRaw instanceof User) {
            loggedUser = (User) principalRaw;
            if (loggedUser.getId() == userId) {
                return true;
            }
        }
        return false;
    }
}
最后是导致错误的测试:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = StockController.class)
@Import({WebMvcConfig.class, UserSecurity.class})
public class StockControllerTest {
@Autowired
MockMvc mockMvc;

//autowired correctly (Bean exists in Context)
@Autowired
UserSecurity userSecurity;

@Test
@WithMockUser("mockUser")
public void TestControllerSecret() throws Exception {
    mockMvc.perform(get("/test/user/1")).andExpect(status().isOk());
}
正如您所看到的,我注入usersecuritybean只是为了测试目的,以检查bean是否存在于Spring上下文中。我想知道@WebMvcTest注释是否会阻止bean的创建,但显然不会。豆子注射正确


不知何故,安全访问检查中的spEL无法识别它,并抛出上述错误

当我创建新的测试类时,它首先使用全Spring自动配置(@SpringBootTest而不是@SpringMvcTest),然后手动创建mockMvc,测试方法工作正常。我还尝试使用配置和bean而不是组件创建UserSecurity bean(@WebMvcTest不应该处理组件bean),这没有改变任何事情。