【问题标题】:Spring Boot WebMvcTest with custom filter difficulties具有自定义过滤器困难的 Spring Boot WebMvcTest
【发布时间】:2020-01-10 09:34:27
【问题描述】:

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

像这样

@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(没有可用的 UserService 类型的合格 bean)

我知道我可以将它作为集成测试运行,但实际上它只是测试控制器,除了自定义过滤器和 Spring Security 之外,没有必要这样做。

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

【问题讨论】:

    标签: spring-boot spring-security dependency-injection spring-test spring-boot-test


    【解决方案1】:

    从docs 开始,@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.. 
         }
    }
    

    同样适用于由@WebMvcTest自动注册为spring bean的所有bean的所有依赖项,其中包括@Controller、@ControllerAdvice、@JsonComponent、Converter、GenericConverter、Filter、@ 987654333@和HandlerMethodArgumentResolver。

    【讨论】:

    • 还有其他方法可以解决这个问题吗?我有另一个处理 JWT 数据的服务,实际上没有必要模拟或弄乱它,因为它完全是技术性的。我应该将该服务设为静态吗? (它必须与 DI 一起使用,对吧?)
    • 不确定。 @MockBean 方法在对控制器进行单元测试时非常有意义,因为最后,您仍然必须模拟它的所有依赖项。那么在使用@MockBean 时,您真正关心的是什么?
    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 2017-03-13
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2018-05-25
    相关资源
    最近更新 更多