org.junit.rules.MethodRule和org.junit.rules.TestWatchman已被弃用。
在https://github.com/junit-team/junit/pull/519上有一个有趣的注解:“许多开发人员是坚持使用MethodRule的合法理由,JUnit团队没有计划取消对MethodRule的支持……”
http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TestWatchman.html documents:“已弃用。MethodRule已弃用。请使用TestWatcher实现TestRule。”并提供了一些示例代码。
将这些标记为已弃用背后的原因是什么?TestWatcher和过时的TestWachman之间的权衡是什么?你有关于这个特定主题的概要或概述的很好的链接吗?
发布于 2012-10-19 16:10:17
原因很简单,TestRule计划取代MethodRule。MethodRule是在4.7中引入实现的,它是一个具有一种方法的接口:
Statement apply(Statement base, FrameworkMethod method, Object target)FrameworkMethod (几乎)是一个内部JUnit类,它从一开始就不应该公开。object是将在其上运行方法的对象,因此,例如,您可以使用反射来修改测试的状态。
TestRule是在4.9中引入的,但是:
Statement apply(Statement base, Description description)Description是一个包含测试描述的不可变POJO。在测试中修改状态的方法是使用TestRule在测试中正确封装。这是一个完全干净的设计。
除了TestWatcher有更好的错误处理之外,TestWatchman(MethodRule)和TestWatcher(TestRule)之间的具体区别很小,因此应该优先使用这一点。两者都有可重写的方法,如succeeded()、failed()、starting()、finished()。
public static class WatchmanTest {
private static String watchedLog;
@Rule
public TestWatcher watchman= new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
watchedLog+= description + "\n";
}
@Override
protected void succeeded(Description description) {
watchedLog+= description + " " + "success!\n";
}
};
@Test
public void fails() {
fail();
}
@Test
public void succeeds() {
}
}TestWatcher(TestRule)处理覆盖方法中的异常。如果抛出异常,则测试方法在执行测试后失败,而不是在执行期间失败。
有关更多信息,请参见TestWatcher和TestWatchman
https://stackoverflow.com/questions/12965423
复制相似问题