2017-08-24 30 views
1

Springブートでアプリケーションを作成しています。このサービスは、に沿って展開されます(私がまた、開発した)他のアプリケーションにRESTエンドポイントに接続しますSpringブートでJUnitテストでBeanを作成する際にエラーが発生しました。

@Service 
public class MyService { 

    @Value("${myprops.hostname}") 
    private String host; 

    public void callEndpoint() { 
     String endpointUrl = this.host + "/endpoint"; 
     System.out.println(endpointUrl); 
    } 
} 

:私はそのように見えるのサービスを作成しました。そのため、application.propertiesファイル(-default、-qa、-dev)でhostnameをカスタマイズする必要があります。

私のアプリケーションはうまく構築されています。このサービスを呼び出すコントローラーを作成してテストし、hostフィールドにapplication.propertiesの正しいプロパティを設定します。

このクラスのテストを作成しようとすると問題が発生します。 私はこの方法を試してみてください。

@RunWith(SpringRunner.class) 
public class MyServiceTest { 

    @Autowired 
    private MyService myService; 

    @Test 
    public void callEndpoint() { 
     myService.callEndpoint(); 
    } 
} 

私は例外受け取る:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ge.bm.wip.comp.processor.service.MyServiceTest': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ge.bm.wip.comp.processor.service.MyService' available: expected at least 1 bean which qualifies as autowire candidate.

そして、いくつかのより多くのネストされた例外を。それが助けになるなら、私はそれらを掲示することができます。 何らかの理由でSpringRunnerがSpringコンテキストでこのテストを起動しないため、Bean MyServiceが表示されないことが考えられます。

どのように修正できますか?私は、通常の初期化を試みた:

private MyService myService = new myService(); 

をが、その後hostフィールドには、あなたが同様に@SpringBootTestを使用してテストに注釈を付ける必要がありnull

答えて

2

です。

試してみてください。

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class MyServiceTest { 

    @Autowired 
    private MyService myService; 

    @Test 
    public void callEndpoint() { 
     myService.callEndpoint(); 
    } 
} 
関連する問題