若是咱们想再多个测试类中服用编写的@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