Spring引导无法为服务测试类自动装配存储库bean

时间:2017-01-08 18:49:04

标签: java spring spring-boot autowired spring-test

我正在为我的应用程序使用模拟存储库 以下是服务外观的摘录:

@Service
public class WeatherStationService {

    @Autowired
    private WeatherStationRepositoryMock weatherRepository;

这是存储库代码:

@Repository
public class WeatherStationRepositoryMock {

    @Getter
    private List<WeatherStation> stations = new ArrayList<>(
            Arrays.asList(
                    new WeatherStation("huston", "Huston station", RandomGenerator.getRandomGeoInformation()),
                    new WeatherStation("colorado", "Colorado station", RandomGenerator.getRandomGeoInformation())
            )
    );

当我使用@SpringBootApplication执行 main()时,它可以正常工作。

但是,当我想运行测试类时:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MockConfig.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class WeatherStationServiceTest {

    @Autowired
    @Real
    private WeatherStationService weatherService;

以下堆栈跟踪失败:

  

引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有'edu.lelyak.repository.WeatherStationRepositoryMock'类型的限定bean可用:预计至少有1个bean有资格作为autowire候选者。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

这是MockConfig的内容:

@Configuration
public class MockConfig {
    //**************************** REAL BEANS ******************************
    @Bean
    @Real
    public WeatherStationService weatherServiceReal() {
        return  new WeatherStationService();
    }

Real是实例的标记注释:

@Retention(RUNTIME)
@Qualifier
public @interface Real {
}

我可以通过服务的下一次初始化来修复它:

@Service
public class WeatherStationService {
    private WeatherStationRepositoryMock weatherRepository = new WeatherStationRepositoryMock();

工作正常。

为什么会这样? 如何修复自定义存储库类的自动装配?

1 个答案:

答案 0 :(得分:1)

@SpringBootApplication隐式定义@ComponentScan,它扫描bean的所有子包。 当您使用MockConfig&#39}运行测试时,它不会扫描bean。

解决方案 - 使用@ComponentScan或在MockConfig中定义bean

(1)使用@ComponentScan:

@Configuration
@ComponentScan //Make sure MockConfig is below all beans to discover
public class MockConfig {
    @Bean
    @Real
    public WeatherStationService weatherServiceReal() {
        return  new WeatherStationService();
    }
}

(2)或定义所需的bean:

@Configuration
public class MockConfig {
    @Bean
    @Real
    public WeatherStationService weatherServiceReal() {
        return  new WeatherStationService();
    }

    @Bean
    public WeatherStationRepositoryMock weatherStationRepository() {
        return new WeatherStationRepositoryMock()
    }
}