2016-08-05 9 views
0

Spring起動アプリケーションとしてアプリケーションを起動すると、ServiceEndpointConfigが正しく自動配線されます。しかし、Junitテストとして実行すると、次の例外が発生します。私はapplication.ymlファイルと異なるプロファイルを使用しています。Springユニットテスト

@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を作成していますクラス。 importディレクティブは、SpringがスキャンでMyServiceImplを選択したときにのみ処理されます。それ以外の場合は、設定として扱われません。

あなたのクラス間の関係は絡まっています。依存性注入の全体のポイントは、のそれはそれ自体を作成する必要はありませんどのようなものと言う必要があるということです。この組織は、内部的に依存関係を手動で作成するよりも優れていません。

代わりに、

  • MyServiceImplMyServiceImpl
  • 使用コンストラクタ・インジェクションから@Configuration@Importディレクティブを排除し、必要なすべての設定クラスが含まれるように
  • 変更あなたのテスト構成。コンストラクタ注射で

、単にnew MyServiceImpl(testServiceConfig)を作成することにより、実際のユニット試験と全くSpringコンテキストをバイパスし、これを実行することができるかもしれません。

関連する問題