现在的答案是在您的套件中创建一个。该规则将在运行每个测试类之前或之后(取决于实现方式)调用。您可以扩展/实现几个不同的基类。类规则的好处在于,如果您不将它们实现为匿名类,那么您可以重用代码!@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 );
}
}