1. TestRule

  • TestRule@Before,@After,@BeforeClass,@AfterClass功能类似,但是更加强大;
  • JUnit 识别TestRule的两种方式:
    • 方法级别:@Rule;
    • 类级别:@ClassRule;
  • TestRule的实现类:
    • ErrorCollector
    • ExpectedException
    • ExternalResource
    • TemporaryFolder
    • TestName
    • TestWatcher
    • Timeout
    • Verifier
// org.juit.rules.TestRule 源码
public interface TestRule{
// 只有一个抽象方法
// 子类需要对Statement进行修改
// 返回值:可能是原来的base,或者装饰之后的base,或者一个全新的base
Statement apply(Statement base, Description description);
} // org.junit.runners.model.Statement
public abstract class Statement{
// 只有一个抽象方法
public abstract void evalute() throws Throwable;
} // org.junit.rules.ExpectedException
public class ExpectedException implements TestRule{ ...(略) // apply 方法的实现
public Statement apply(Statement base, Description description){
return new ExpectedExceptionStatement(base);
} // 对Statement的处理
private class ExpectedExceptionStatement extends Statement{
private final Statement next; public ExpectedExceptionStatement(Statement base){
next = base;
} @Override
public void evalute() throws Throwable{
try{
next.evalute();
}catch(Throwable e){
handleException(e);
return;
}
if(isAnyExceptionExpected()){
failDueToMissingException();
}
}
} ...(略)
}

1.1 测试示例

// 自定义Statement
public class MyStatement extends Statement{
private final Statement myBase; public MyStatement(Statement base){
this.myBase = base;
} @Override
public void evalute() throws Throwable{
System.out.println("方法执行开始之前");
try{
myBase.evalute();
}finally{
System.out.println("方法执行之后");
}
}
} // 自定义Rule
public class MyRule implements TestRule{
@Override
public Statement apply(Statement base, Description description){
return new MyStatement(base);
}
} // 自定义Test
public class MyTest{
@Rule
public MyRule myRule = new MyRule(); @Test
public void testCase(){
System.out.println("测试运行....");
}
} // 控制台输出:
方法执行开始之前
测试运行....
方法执行之后

参考资料:

JUnit之Rule的使用

05-28 10:03