Testrule declares factory methods
Testrule isFactory method modeCreator role in -- declare the factory method.
package org.junit.rules;import org.junit.runner.Description;import org.junit.runners.model.Statement;public interface TestRule {Statement apply(Statement base, Description description);}
To use rule, the test programmer must write the code:
1. mystatement -- one of statementNew decoration object. (Example of the use of JUnit rule), the status is equivalent to expectexception.
package rule;import static tool.Print.*;//pln(Object)import org.junit.runners.model.Statement;/** * * @author yqj2065 */public class MyStatement extends Statement { private final Statement base; public MyStatement( Statement base ) { this.base = base; } @Override public void evaluate() throws Throwable { pln( "before...sth..sth" ); try { base.evaluate(); } finally { pln( "after...sth..sth" ); } }}
2. A specific factory, that is, defining the factory Method
Subclass of testrule. Myrule will create a statement
New decoration object mystatement. Similar to the general usage of the factory method model, the specific factory and specific products correspond one by one.
package rule;import org.junit.rules.TestRule;import org.junit.runners.model.Statement;import org.junit.runner.Description;public class MyRule implements TestRule { @Override public Statement apply(Statement base, Description description) { return new MyStatement( base ); }}
3. Use a new decoration object
The user class blockjunit4classrunner uses the built-in statement decoration objects of JUnit such as expectexception;The statement decoration object compiled by the test programmer needs to be embedded into the unit test class through @ rule..
package rule;import org.junit.Rule;import org.junit.Test;public class MyTest { @Rule public MyRule myRule = new MyRule(); @Test() public void xx() { System.out.println( "xx()..." ); }}
Run mytest in the development environment and output:
Before... ......
XX ()...
After...
Rulechain
Junit4.10 source code analysis: 5.2 Rule