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

Gan*_*ute 10 unit-testing spring-mvc spring-boot spring-boot-test

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

@RestController
public class VehicleController {
    @Autowired 
    private VehicleService vehicleService = null; 
    ... 

}
Run Code Online (Sandbox Code Playgroud)

虽然测试类看起来像

@RunWith(SpringRunner.class)
@WebMvcTest(VehicleController.class)
public class VehicleControllerTest {
    @Autowired 
    private MockMvc mockMvc = null;

    @MockBean 
    private VehicleService vehicleServie = null; 

    @Test
    public void test() {
       ...
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,它失败并出现以下错误

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)}
Run Code Online (Sandbox Code Playgroud)

这里,SomeOtherRepository不在给定的控制器或服务中使用。

如果我这样做@MockBean测试SomeOtherRepository有效,但其余存储库也会出现同样的问题。

@MockBean private SomeOtherRepository someOtherRepository = null
...
# Bunch of other repositories
Run Code Online (Sandbox Code Playgroud)

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

Heu*_*kos 4

您已指定

@WebMvcTest(VehicleController.class)
Run Code Online (Sandbox Code Playgroud)

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

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

@WebMvcTest(controllers = VehicleController.class, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = CustomUserDetailsService.class)
Run Code Online (Sandbox Code Playgroud)