unit-testing - @WebMvcTest 没有类型存储库的限定 bean
问题描述
我正在编写一个控制器测试,其中控制器看起来像
@RestController
public class VehicleController {
@Autowired
private VehicleService vehicleService = null;
...
}
虽然测试类看起来像
@RunWith(SpringRunner.class)
@WebMvcTest(VehicleController.class)
public class VehicleControllerTest {
@Autowired
private MockMvc mockMvc = null;
@MockBean
private VehicleService vehicleServie = null;
@Test
public void test() {
...
}
}
当我运行此测试时,它失败并出现以下错误
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.database.repositories.SomeOtherRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
在这里,SomeOtherRepository
没有在给定的控制器或服务中使用。
如果我@MockBean
为SomeOtherRepository
测试工作而做,但其他存储库也会出现同样的问题。
@MockBean private SomeOtherRepository someOtherRepository = null
...
# Bunch of other repositories
理想情况下,我不应该关心除了我正在使用的存储库之外的所有存储库。我在这里想念什么?我怎样才能避免写一堆@MockBean
s?
解决方案
您已指定
@WebMvcTest(VehicleController.class)
这很好,但是您可能会从其他依赖项中找到一些 bean,例如 custom UserDetailsService
、一些自定义验证,或者@ControllerAdvice
也被引入。
您可以使用排除过滤器排除这些 bean 。
@WebMvcTest(controllers = VehicleController.class, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = CustomUserDetailsService.class)
推荐阅读
- node.js - express-validator 并在错误后填充输入字段
- mysql - IN 子句在 MYSQL 触发器中的 WHERE 条件下不起作用
- python - 如何使用来自分组的统计信息将列添加到数据框中
- java - 如何将日期时间字段保存到 cosmosdb“SQL API / DocumentDb”?
- javascript - 移动浏览器中后退按钮后的事件
- flutter - 如何更改 CupertinoDatePicker 的背景颜色
- mongodb - 这个关于在 MongoDB 中预填充数据的提示是否正确?
- java - 使用
在 MyBatis3 中,项目列表为 NULL - android - Flutter Switch 在 Android 上没有动画,但在 iOS 上
- sql-server - 从 BLOB 数据库备份中获取逻辑文件名