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 @MockBean
s?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With