2016-08-05 137 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上下文並運行此作爲實際單元測試。