@Before/@After Vs @Rule
如果我们想再多个测试类中服用编写的@Before
装饰的setUp()
方法和@After
装饰的tearDown()
方法时,可以考虑使用@Rule
注解。
在使用@Rule
注解时,@Rule
修饰的类需要实现TestRule
或MethodRule
(计划被@TestRule
所取代)接口中的apply
方法。
@Rule Vs @ClassRule
@ClassRule
对标@BeforeClass/@AfterClass
@Rule
对标@Before/@After
@ClassRule
是 static方法,@Rule
不是。但@ClassRule
和@Rule
修饰的成员变量都必须为public
。
TestRule 示例:
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
。
参考资料:
- https://stackoverflow.com/questions/43193188/junit-before-vs-rule
- https://www.baeldung.com/junit-4-rules
- https://medium.com/@elye.project/all-about-testrule-a-steroid-before-after-a74ef421e3e5
- http://sandordargo.com/blog/2017/08/08/rules-in-junit