在Junit4中,如何基于@Test注释更改@Before行为

发布于 2024-12-12 08:27:09 字数 418 浏览 0 评论 0 原文

我希望我的 @Before 方法知道当前正在执行的测试注释,以便 @Before 方法可以执行各种操作。具体来说,现在我们的 @Before 总是执行各种初始化步骤,例如重新加载数据库等。我希望能够编写这样的代码:

@Before
void setUp() {
    if (testMethod.hasAnnotation(@NeedsDatabase)) {
        reloadDatabase();
    }
}

我想一种解决方案是使用 @Rule 进行数据库初始化,但这将是实施起来很复杂,我们现有的基础设施已经在 @setUp 中处理了这个问题。我们已经有了一个自定义的 Runner,并且所有测试都扩展了一个共享基类(如果有帮助的话)。

我试图想出一种方法来做到这一点,但我不知道 JUnit4 中有什么可用的。

I would like my @Before method to know the currently executing tests Annotations, so that the @Before method can do various things. Specifically, right now our @Before always does various initialization steps like reloading the database, etc. I would like to be able to write code like this:

@Before
void setUp() {
    if (testMethod.hasAnnotation(@NeedsDatabase)) {
        reloadDatabase();
    }
}

I guess one solution would be to use a @Rule for DB initialization, but this would be complicated to implement and our existing infrastructure already handles this in @setUp. We already have a custom Runner and all tests extend a shared base class, if that helps.

I tried to think of a way to do this, but I don't know what is available in JUnit4.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

懒猫 2024-12-19 08:27:10

您可以使用 @RunWith 注释,并创建您自己的 < a href="http://junit.sourceforge.net/javadoc/org/junit/runners/ParentRunner.html" rel="nofollow">ParentRunner 扫描您的 @NeedsDatabase 注释并适当地处理设置。

You could use the @RunWith annotion, and create your own ParentRunner that scans for your @NeedsDatabase annotation and handles setup appropriately.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文