首页 > 解决方案 > @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没有在给定的控制器或服务中使用。

如果我@MockBeanSomeOtherRepository测试工作而做,但其他存储库也会出现同样的问题。

@MockBean private SomeOtherRepository someOtherRepository = null
...
# Bunch of other repositories

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

标签: unit-testingspring-mvcspring-bootspring-boot-test

解决方案


您已指定

@WebMvcTest(VehicleController.class)

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

您可以使用排除过滤器排除这些 bean 。

@WebMvcTest(controllers = VehicleController.class, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = CustomUserDetailsService.class)

推荐阅读