答えは@ClassRule、スイート内に を作成することです。ルールは、各テスト クラスが実行される前または後に (実装方法に応じて) 呼び出されます。拡張/実装できる基本クラスがいくつかあります。クラス ルールの良いところは、それらを匿名クラスとして実装しなければ、コードを再利用できることです!
それらに関する記事は次のとおりです。http://java.dzone.com/articles/junit-49-class-and-suite-level-rules
これらの使用方法を説明するためのサンプル コードを次に示します。はい、些細なことですが、開始するのに十分なほどライフサイクルを説明する必要があります。
最初にスイートの定義:
import org.junit.*;
import org.junit.rules.ExternalResource;
import org.junit.runners.Suite;
import org.junit.runner.RunWith;
@RunWith( Suite.class )
@Suite.SuiteClasses( {
RuleTest.class,
} )
public class RuleSuite{
private static int bCount = 0;
private static int aCount = 0;
@ClassRule
public static ExternalResource testRule = new ExternalResource(){
@Override
protected void before() throws Throwable{
System.err.println( "before test class: " + ++bCount );
sss = "asdf";
};
@Override
protected void after(){
System.err.println( "after test class: " + ++aCount );
};
};
public static String sss;
}
そして今、テストクラスの定義:
import static org.junit.Assert.*;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
public class RuleTest {
@Test
public void asdf1(){
assertNotNull( "A value should've been set by a rule.", RuleSuite.sss );
}
@Test
public void asdf2(){
assertEquals( "This value should be set by the rule.", "asdf", RuleSuite.sss );
}
}