spring-boot - 具有自定义过滤器困难的 Spring Boot WebMvcTest
问题描述
我正在通过使用多个@Service
s 的自定义过滤器使用 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
,这似乎不对。
解决方案
从文档中,@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
,WebMvcConfigurer
和HandlerMethodArgumentResolver
.
推荐阅读
- sql - 从具有面积总和的表中选择查询
- javascript - 优化缩小 JS 的 TypeScript 编译和调试
- php - 如何在从 Laravel 到 Kotlin 的异常中获取响应
- javascript - 尝试在 ReactJS 中设置数组的状态,但不确定如何映射
- java - 在Java中将十六进制字符解码为ASCII时的奇怪行为
- c# - 如何修复由 c# 套接字发送的未完成消息
- windows - 无法删除文件 - Windows 10,权限问题?
- jenkins-groovy - 如何读取詹金斯旧版本注入的环境变量
- javascript - 无法编写在渲染中调用 moment 方法的组件的快照测试
- c++ - C++ inline asm 在 32 位寄存器中移动 WCHAR