若是咱們想再多個測試類中服用編寫的@Before
裝飾的setUp()
方法和@After
裝飾的tearDown()
方法時,能夠考慮使用@Rule
註解。
在使用@Rule
註解時,@Rule
修飾的類須要實現TestRule
或MethodRule
(計劃被@TestRule
所取代)接口中的apply
方法。app
@ClassRule
對標@BeforeClass/@AfterClass
@Rule
對標@Before/@After
@ClassRule
是 static方法,@Rule
不是。但@ClassRule
和@Rule
修飾的成員變量都必須爲public
。ide
public class TestMethodNameLogger implements TestRule { private static final Logger LOG = LoggerFactory.getLogger(TestMethodNameLogger.class); @Override public Statement apply(Statement base, Description description) { logInfo("Before test", description); try { return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); } }; } finally { logInfo("After test", description); } } private void logInfo(String msg, Description description) { LOG.info(msg + description.getMethodName()); } }
當咱們在實現apply
方法時,咱們必須返回一個Statement
的實例。這個實例表明着咱們在Junit運行時中的測試。在調用evaluate()
方法時測試被執行。 測試
Junit的Rule可能會以任意順序執行。若是想要控制多個Rule的執行順序,可使用@RuleChain
。lua