Spring boot Spring Boot WebMVCTTest具有自定义筛选器困难

Spring boot Spring Boot WebMVCTTest具有自定义筛选器困难,spring-boot,spring-security,dependency-injection,spring-test,spring-boot-test,Spring Boot,Spring Security,Dependency Injection,Spring Test,Spring Boot Test,我通过使用多个@Service的自定义过滤器使用JWT身份验证 像这样 @Component public class JwtAuthentiationFilter extends OncePerRequestFilter { private final UserService; ... } (我正在构造函数中自动连接服务) 现在,我想测试一个控制器: @RestController @RequestMapping(...) public class COmputerDevic

我通过使用多个
@Service
的自定义过滤器使用JWT身份验证

像这样

@Component
public class JwtAuthentiationFilter extends OncePerRequestFilter {
    private final UserService;
    ...
}
(我正在构造函数中自动连接服务)

现在,我想测试一个控制器:

@RestController
@RequestMapping(...)
public class COmputerDeviceController {

    @GetMapping
    @PreAuthorize("hasAuthority('devices)")
    public List<Device> getDevices() {
         ...
    }
}
问题源于过滤器的使用-当尝试运行测试时,我得到了
NoSuchBeanDefinitionException
(没有类型为
UserService
的合格bean可用)

我知道我可以将其作为集成测试运行,但实际上它只是测试控制器,除了自定义过滤器和Spring安全性之外,不需要这样做

我怎样才能解决这个问题?我尝试了不同的解决方案,比如添加
@ComponentScan.Filter
,并手动包含依赖项,但最后我不得不提供
entitymanager
,这似乎不正确。

从中,
@WebMvcTes
jwtauthenticationfilter
注册为Springbean,但不注册其依赖项,您必须使用
@MockBean
来声明这些依赖项


@RunWith(SpringRunner.class)
@WebMvcTest(计算机设备控制器类)
公共类计算机设备控制器测试{
@自动连线
私有MockMvc;
@蚕豆
私人用户服务;
@WithMockUser
@试验
public void test()引发异常{
//然后您可以在此处存根用户服务行为。。
}
}

这同样适用于通过
@WebMvcTest
自动注册为Springbean的所有bean的所有依赖项,这些bean包括
@Controller
@ControllerAdvice
@JsonComponent
Converter
过滤器
webmvcconfiguer
,还有
HandlerMethodArgumentResolver

还有其他方法吗?我有另一个处理JWT数据的服务,真的没有必要去模仿或弄乱它,因为它完全是技术性的。我应该让那个服务变成静态的吗?(它不必与DI一起使用,对吗?)
@MockBean
方法在对控制器进行单元测试时非常有意义,因为最终,您仍然必须模拟它的所有依赖项。那么,在使用
@MockBean
时,您真正关心的是什么呢?
@RunWith(SpringRunner.class)
@WebMvcTest(ComputerDeviceController.class)
public class ComputerDeviceControllerTest {

     @Autowired
     private MockMvc mvc;

     @WithMockUser
     @Test
     public void test() throws Exception {
         ...
     }
}