@RunWithと@ContextConfigurationで注釈を付けJUnitテストでSpringコンテキストにアクセスするには?

StackOverflow https://stackoverflow.com/questions/2425015

質問

私はテストクラスを以下している。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest {

  @Autowired
  MyService service;
...

}

これは、このような方法の一つでプログラムservices-test-config.xmlにアクセスすることは可能ですか?同様ます:

ApplicationContext ctx = somehowGetContext();
役に立ちましたか?

解決

テストがあまりにものSpring Beanのようにインスタンス化されますので、あなただけのApplicationContextAwareインターフェイスを実装する必要があります:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

他のヒント

これはあまりにも正常に動作します:

@Autowired
ApplicationContext context;

あなたのテストクラスは、SpringのJUnitクラスを拡張する場合
(例えば、AbstractTransactionalJUnit4SpringContextTestsまたはAbstractSpringContextTestsを拡張する他のクラス)、あなたはgetContext()メソッドを呼び出すことにより、アプリケーション・コンテキストにアクセスすることができます。
パッケージは、のJavadoc にチェックorg.springframework .TESTます。

これはApplicationContextを使用してSpringClassRuleクラスのインスタンスを注入することが可能です そして、SpringMethodRuleルール。あなたが使用したい場合、それは非常に便利かもしれません 別の非春のランナー。ここでは例があります:

@ContextConfiguration(classes = BeanConfiguration.class)
public static class SpringRuleUsage {

    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();

    @Autowired
    private ApplicationContext context;

    @Test
    public void shouldInjectContext() {
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top