Ganesh Satpute
Ganesh Satpute

Reputation: 3961

@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?

Upvotes: 11

Views: 9059

Answers (2)

Numan Karaaslan
Numan Karaaslan

Reputation: 1645

Your VehicleService depends on SomeOtherRepository, so you have to mock it too in your test class. Try adding:

@MockBean private SomeOtherRepository someOtherRepository

in your VehicleControllerTest class.

Upvotes: 0

Heuriskos
Heuriskos

Reputation: 532

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)

Upvotes: 4

Related Questions