Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@WebMvcTest No qualifying bean of type repository

I'm writing a controller test where controller looks like

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

}

While the test class looks like

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

    @MockBean 
    private VehicleService vehicleServie = null; 

    @Test
    public void test() {
       ...
    }
}

When I run this test it fails with the following error

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)}

Here, SomeOtherRepository is not used in a given controller or service.

If I do @MockBean for SomeOtherRepository the test works but the same problem occurs for the rest of the repositories.

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

Ideally I should not be concerned about all the repositories except the one's I'm using. What am I missing here? How can I avoid writing bunch of @MockBeans?

like image 822
Ganesh Satpute Avatar asked Oct 17 '22 11:10

Ganesh Satpute


1 Answers

You have specified

@WebMvcTest(VehicleController.class)

which is fine, however you might find some beans from other dependencies, such as a custom UserDetailsService, some custom validation, or @ControllerAdvice that are also being brought in.

You can exclude these beans by using exclude filters.

@WebMvcTest(controllers = VehicleController.class, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = CustomUserDetailsService.class)
like image 189
AlexB Avatar answered Oct 21 '22 09:10

AlexB