質問

Spring は JUnit を非常によくサポートしています。とともに RunWith そして ContextConfiguration 注釈、物事は非常に直感的に見えます

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:dao-context.xml")

このテストは、Eclipse と Maven の両方で正しく実行できます。TestNGにも同様のものはあるのだろうか。この「次世代」フレームワークへの移行を検討していますが、Spring でのテストに適合するものが見つかりませんでした。

役に立ちましたか?

解決

TestNG でも動作します。あなたの テスト クラスはする必要があります 伸ばす 次のクラスのいずれか:

他のヒント

ここでは私のために働いた例は次のとおりです。

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

@Test
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestValidation extends AbstractTestNGSpringContextTests {

    public void testNullParamValidation() {
        // Testing code goes here!
    }
}

Spring と TestNG はうまく連携しますが、注意すべき点がいくつかあります。AbstractTestNGSpringContextTests のサブクラス化とは別に、標準の TestNG セットアップ/ティアダウン アノテーションとどのように相互作用するかを認識する必要があります。

TestNG には 4 つのレベルのセットアップがあります

  • BeforeSuite
  • テスト前
  • 授業前
  • Beforeメソッド

これは、まさに期待どおりに実行されます (自己文書化 API の好例)。これらはすべて、同じレベルのメソッドの名前である String または String[] を取ることができる「dependsOnMethods」と呼ばれるオプションの値を持っています。

AbstractTestNGSpringContextTests クラスには、 springTestContextPrepareTestInstance という BeforeClass アノテーション付きメソッドがあり、その中で autowired クラスを使用している場合は、このメソッドに依存するようにセットアップ メソッドを設定する必要があります。メソッドの場合、自動配線について心配する必要はありません。これは、クラス メソッドの前にテスト クラスが設定されるときに自動配線が行われるためです。

これで、BeforeSuite のアノテーションが付けられたメソッドで autowired クラスをどのように使用できるかという問題が残ります。これは、 springTestContextPrepareTestInstance を手動で呼び出すことで実行できます。デフォルトではこれを行うように設定されていませんが、私は何度か成功しました。

そこで、Arup の例の修正バージョンを説明します。

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

@Test
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestValidation extends AbstractTestNGSpringContextTests {

    @Autowired
    private IAutowiredService autowiredService;

    @BeforeClass(dependsOnMethods={"springTestContextPrepareTestInstance"})
    public void setupParamValidation(){
        // Test class setup code with autowired classes goes here
    }

    @Test
    public void testNullParamValidation() {
        // Testing code goes here!
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top