我希望我的 @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.
发布评论
评论(2)
您可以使用 @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.
将@Rule与TestWatcher一起使用并实现starting()
http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/TestWatcher.html#starting%28org.junit.runner.Description%29
Use @Rule with TestWatcher and implement starting()
http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/TestWatcher.html#starting%28org.junit.runner.Description%29