9

私は Spring を初めて使用し、Web アプリケーション用の一連の JUnit 4.7 統合テストに取り組んでいます。次の形式の実際のテストケースがいくつかあります。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" })

public class myTest {
    @Test
    public void testCreate() {
            //execute tests
            ....
    }
}

私のアプリケーションには、テスト中の多くの外部依存関係があり、そのすべてにtestContext.xmlのロードによって初期化される Bean があります。これらの外部依存関係の一部では、必要なリソースを初期化して破棄するためにカスタム コードが必要です。

このコードを必要とするすべてのテスト クラスでこのコードを複製するのではなく、共通の場所にカプセル化したいと考えています。私の考えは、次のように、別のコンテキスト定義と、 SpringJUnit4ClassRunnerを拡張し、@ContextConfiguration アノテーションと関連するカスタム コードを含むカスタム ランナーを作成することでした。

import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//load the context applicable to this runner
@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" })

public class MyCustomRunner extends SpringJUnit4ClassRunner {

    public MyCustomRunner(Class<?> clazz) throws InitializationError {
        super(clazz);           
    }

    @Override
    protected Statement withBeforeClasses(Statement statement) {
        // custom initialization code for resources loaded by testContext.xml
                ...

        return super.withBeforeClasses(statement);
    }

    @Override
    protected Statement withAfterClasses(Statement statement) {
        // custom cleanup code for resources loaded by testContext.xml
                ....

        return super.withAfterClasses(statement);
    }

}

次に、各テスト クラスに該当するランナーを次のように指定させることができます。

@RunWith(MyCustomRunner)

これを行うと、テストが実行され、適切なwithBeforeClassesおよびwithAfterClassesメソッドが実行されます。ただし、テストクラスに applicationContext が返されず、すべてのテストが次のように失敗します。

java.lang.IllegalArgumentException: NULL 'contextLoader' で ApplicationContext をロードできません。テスト クラスに @ContextConfiguration のアノテーションを付けることを検討してください。

コンテキストは、各テスト クラスで @ContextConfiguration アノテーションを指定した場合にのみ正しく読み込まれます。理想的には、このアノテーションが読み込みを担当するリソースのハンドラー コードと一緒に存在するようにしたいと考えています。これが私の質問につながります-カスタムランナークラスからSpringコンテキスト情報をロードすることは可能ですか?

4

1 に答える 1

13

基本テスト クラスを作成することができます -@ContextConfiguration継承することができ@Beforeます@After

@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" }) 
public abstract class myBaseTest { 
    @Before
    public void init() {
        // custom initialization code for resources loaded by testContext.xml 
    }

    @After
    public void cleanup() {
        // custom cleanup code for resources loaded by testContext.xml
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
public class myTest extends myBaseTest { ... }
于 2011-04-20T17:08:36.140 に答える