gpt4 book ai didi

java - 为什么不推荐使用 JUnit MethodRule 和 TestWatchman?

转载 作者:太空狗 更新时间:2023-10-29 22:53:44 25 4
gpt4 key购买 nike

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文件:“已弃用。MethodRule 已弃用。改为使用 TestWatcher 实现 TestRule。”并提供了一些示例代码。

将这些标记为已弃用的原因是什么?TestWatcher 和已弃用的 TestWachman 之间的权衡是什么?您是否有关于此特定主题的概要或概述的好链接?

最佳答案

原因很简单,TestRule 是为了取代MethodRuleMethodRule是4.7引入的实现,是一个方法接口(interface):

Statement apply(Statement base, FrameworkMethod method, Object target)

FrameworkMethod(几乎)是一个内部 JUnit 类,一开始就不应该公开它。 object 是方法将在其上运行的对象,因此例如,您可以使用反射修改测试的状态。

TestRule 是在 4.9 中引入的,然而,是:

Statement apply(Statement base, Description description)

Description 是包含测试描述的不可变 POJO。在测试中修改状态的方法是使用 TestRule 在测试中正确封装。这是一个更简洁的设计。

TestWatchman(MethodRule)TestWatcher(TestRule) 之间的具体区别很小,除了 TestWatcher 有更好的错误处理,所以应该优先使用它。两者都有可覆盖的方法,例如 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) 处理覆盖方法中的异常。如果抛出异常,则测试方法会在测试执行后失败,而不是在测试期间失败。

有关详细信息,请参阅 TestWatcherTestWatchman

关于java - 为什么不推荐使用 JUnit MethodRule 和 TestWatchman?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12965423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com