首页 > 解决方案 > 具有自定义过滤器困难的 Spring Boot WebMvcTest

问题描述

我正在通过使用多个@Services 的自定义过滤器使用 JWT 身份验证。

像这样

@Component
public class JwtAuthentiationFilter extends OncePerRequestFilter {
    private final UserService;
    ...
}

(我在构造函数中自动装配服务)

现在,我有一个要测试的控制器:

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

    @GetMapping
    @PreAuthorize("hasAuthority('devices)")
    public List<Device> getDevices() {
         ...
    }
}

我想测试控制器和安全性,如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest(ComputerDeviceController.class)
public class ComputerDeviceControllerTest {

     @Autowired
     private MockMvc mvc;

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

问题来自使用过滤器 - 尝试运行测试时,我得到NoSuchBeanDefinitionException(没有可用类型的合格 bean UserService

我知道我可以将它作为集成测试运行,但实际上它只是测试控制器并且不需要它,除了自定义过滤器和 Spring Security。

我该如何解决这个问题?我尝试了不同的解决方案,例如@ComponentScan.Filter手动添加和包含依赖项,但最后我必须提供entitymanager,这似乎不对。

标签: spring-bootspring-securitydependency-injectionspring-testspring-boot-test

解决方案


文档中,@WebMvcTes将注册JwtAuthentiationFilter为 spring bean 而不是它的依赖项,您必须使用 @MockBean来声明这些依赖项。


@RunWith(SpringRunner.class)
@WebMvcTest(ComputerDeviceController.class)
public class ComputerDeviceControllerTest {

     @Autowired
     private MockMvc mvc;

     @MockBean
     private UserService userService;

     @WithMockUser
     @Test
     public void test() throws Exception {
        //Then you can stub userService behaviour here.. 
     }
}

这同样适用于自动注册为 spring bean 的所有 bean 的所有依赖项,@WebMvcTest其中包括@Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, Filter,WebMvcConfigurerHandlerMethodArgumentResolver.


推荐阅读