Spring と TestNG はうまく連携しますが、注意すべき点がいくつかあります。サブクラス化は別AbstractTestNGSpringContextTests
として、それが標準の TestNG セットアップ/ティアダウン アノテーションとどのように相互作用するかを認識する必要があります。
TestNG には 4 つのレベルのセットアップがあります
- 前スイート
- テスト前
- 授業前
- Beforeメソッド
これはまさに期待どおりに発生します (自己文書化 API の好例)。dependsOnMethods
これらはすべて、同じレベルのメソッドの名前である String または String[] を取ることができるというオプションの値を持っています。
このAbstractTestNGSpringContextTests
クラスには、BeforeClass
と呼ばれる注釈付きのメソッドspringTestContextPrepareTestInstance
があり、自動配線されたクラスを使用している場合は、依存するようにセットアップ メソッドを設定する必要があります。メソッドの場合、クラスメソッドの前にテストクラスがセットアップされているときに発生するため、オートワイヤリングについて心配する必要はありません。
これにより、 で注釈が付けられたメソッドで自動配線されたクラスをどのように使用するかという問題が残りますBeforeSuite
。手動で呼び出すことでこれを行うことができます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!
}
}