gpt4 book ai didi

unit-testing - @WebMvcTest 没有类型存储库的合格 bean

转载 作者:行者123 更新时间:2023-12-03 23:53:51 27 4
gpt4 key购买 nike

我正在编写一个 Controller 测试,其中 Controller 看起来像

@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未在给定的 Controller 或服务中使用。

如果我这样做 @MockBeanSomeOtherRepository测试有效,但其他存储库也会出现同样的问题。
@MockBean private SomeOtherRepository someOtherRepository = null
...
# Bunch of other repositories

理想情况下,除了我正在使用的存储库之外,我不应该关心所有存储库。我在这里缺少什么?我怎样才能避免写一堆 @MockBean ?

最佳答案

您已指定

@WebMvcTest(VehicleController.class)

这很好,但是您可能会从其他依赖项中找到一些 bean,例如自定义 UserDetailsService ,一些自定义验证,或 @ControllerAdvice也被引进。

您可以使用 exclude filters 排除这些 bean。 .
@WebMvcTest(controllers = VehicleController.class, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = CustomUserDetailsService.class)

关于unit-testing - @WebMvcTest 没有类型存储库的合格 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52886858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com