Sydney
Sydney

Reputation: 12212

@WebMvcTest not running due to missing dependency

I want to test my controller by using @WebMvcTest. I @MockBean the dependencies of the controller but when running the test, it fails to start. The application starts correctly when running the main class.

The Test:

@RunWith(SpringRunner.class)
@WebMvcTest(MetricResource.class)
public class MetricResourceTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private MetricService metricService;

    @MockBean
    private MetricMapper metricMapper;

    @Test
    public void test() {
    }

}

The Controller:

@RestController
@RequestMapping("/api/v1/metrics")
public class MetricResource {

    private final MetricService metricService;

    private final MetricMapper metricMapper;

    public MetricResource(MetricService metricService, MetricMapper metricMapper) {
        this.metricService = metricService;
        this.metricMapper = metricMapper;
    }

    @GetMapping
    public ResponseEntity<List<MetricDto>> getMetrics(@RequestParam(required = false) List<String> fields) {
        if (fields == null) {
            fields = new ArrayList<>();
        }
        List<Metric> metrics = metricService.getMetric(fields);
        List<MetricDto> dto = metricMapper.fromMetric(metrics);
        return ResponseEntity.ok(dto);
    }

}

The error:

Description:

Parameter 2 of constructor in com.sps.soccer.service.SoccerService required a bean named 'mongoTemplate' that could not be found.

Action:

Consider defining a bean named 'mongoTemplate' in your configuration.

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'soccerService' defined in file [K:\home\projects\stable\sps-backend\sps-soccer\target\classes\com\sps\soccer\service\SoccerService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'soccerAnalysisRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'soccerAnalysisRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available

The SoccerService has a dependency on SoccerAnalysisRepository which is a MongoRepository. I don't understand why the SoccerService is created by the test since @Service are not scanned by @WebMvcTest.

The application is a Maven multi modules, so I has to explicitly configure the component scanning and repository.

@SpringBootApplication
@ComponentScan(basePackages = {"com.sps.soccer", "com.sps.sdql", "com.sps.core", "com.sps.web"},
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.sdql.configuration.ClockConfiguration.class),
                @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.soccer.configuration.ClockConfiguration.class),
                @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.sdql.configuration.RestConfiguration.class),
                @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.soccer.configuration.RestConfiguration.class)
        })
@EnableMongoRepositories(basePackages = {"com.sps.soccer", "com.sps.sdql", "com.sps.core"})
public class SpsWebApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpsWebApplication.class, args);
    }
}

Upvotes: 1

Views: 5480

Answers (1)

Alexander Polozov
Alexander Polozov

Reputation: 433

You must move all area-specific configuration, like @ComponentScan and @EnableMongoRepositories, to a separate @Configuration file. It's important not to litter the application’s main class with configuration settings that are specific to a particular area of its functionality.

More information: https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-user-configuration

Upvotes: 6

Related Questions