Article From:

1. TestRule

  • TestRuleand@Before,@After,@BeforeClass,@AfterClassThe function is similar, but more powerful;
  • JUnit DistinguishTestRuleThe two ways:
    • Method level:@Rule;
    • Class level:@ClassRule;
  • TestRuleThe implementation class:
    • ErrorCollector
    • ExpectedException
    • ExternalResource
    • TemporaryFolder
    • TestName
    • TestWatcher
    • Timeout
    • Verifier
// org.juit.rules.TestRule Source codePublic interface TestRule{/ / only an abstract method/ / subclasses need to be modified for Statement/ / return value: it may be the original base, or after decoration.Base, or a new baseStatement apply (Statement base, Description description);}/ / org.junit.runnErs.model.StatementPublic abstract class Statement{/ / only an abstract methodPublic abstract void evalutE () throws Throwable;}/ / org.junit.rules.ExpectedExceptionPublic class ExpectedException implemeNTS TestRule{... (slightly)Implementation of / / apply methodPublic Statement apply (Statement base, Description)Description) {Return new ExpectedExceptionStatement (base);}/ / Statement processingPrivate class ExpectedExceptionStatement extends Statement{Private final Statement next;Public ExpectedExceptionStatement (Statement base) {Next = base;}@OverridePublic void evalute () throws Throwable{Try{Next.evALute ();}catch (Throwable E) {HandleException (E);Return;}If (isAnyExceptionExpected ()) {FailDueToMissingException ();}}}... (slightly)}

1.1 test example

// Custom StatementPublic class MyStatement extends Statement{Private final Statement myBase;PuBlic MyStatement (Statement base) {This.myBase = base;}@OverridePublic void eValute () throws Throwable{System.out.println ("before the execution of the method");Try{MyBase.eValute ();}finally{System.out.println ("after the method is executed");}}}/ / custom RulePublic class MyRule implements TestRule{@OverridePublic Statement apply (Statement base, De)Scription description) {Return new MyStatement (base);}}/ / custom TestPublic class MyTesT{@RulePublic MyRule myRule = new MyRule ();@TestPublic void testCase () {System.out.println ("test run...");}}/ / console output:Before the execution of the methodTest run...After the execution of the method

Reference material:
JUnitThe use of Rule

Leave a Reply

Your email address will not be published. Required fields are marked *