2016-08-05 140 views
0

当我将应用程序作为Spring Boot应用程序启动时,ServiceEndpointConfig会正确自动装配。但是,当我作为Junit测试运行时,出现以下异常。我正在使用application.yml文件和不同的配置文件。弹簧单元测试

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = MyServiceContextConfig.class, 
loader = SpringApplicationContextLoader.class) 
@ActiveProfiles({"unit", "statsd-none"}) 
public class MyServiceTest 
{ 
} 

@Configuration 
public class MyServiceContextConfig { 

    @Bean 
    public MyService myServiceImpl(){ 
     return new MyServiceImpl(); 
    } 
} 

@Configuration 
@Component 
@EnableConfigurationProperties 
@ComponentScan("com.myservice") 
@Import({ServiceEndpointConfig.class}) 
public class MyServiceImpl implements MyService { 

    @Autowired 
    ServiceEndpointConfig serviceEndpointConfig; 

} 

@Configuration 
@Component 
@ConfigurationProperties(prefix="service") 
public class ServiceEndpointConfig 
{ 
} 

错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': 
Unsatisfied dependency expressed through field 'serviceEndpointConfig': No qualifying bean of type [com.myservice.config.ServiceEndpointConfig] found 

回答

2

您正在操作MyServiceImpl不一致:在一方面,你正在使用扫描注解,而另一方面,你明确地在配置创建@Bean类。只有在Spring通过扫描选取MyServiceImpl时才会处理导入指令;否则,它不被视为配置。

你们之间的关系纠结在一起;依赖注入的整点是MyServiceImpl应该说它需要什么样的东西但不是自己创建它。这个组织并不比在内部手动创建依赖关系更好。

相反,

  • MyServiceImpl消除@Configuration@Import指令,对MyServiceImpl
  • 使用构造函数注入,与
  • 变化您的测试配置包括所有必要的配置类。

随着构造器注入,你可以通过简单地创建一个new MyServiceImpl(testServiceConfig)完全绕过Spring上下文并运行此作为实际单元测试。