在ScalaTest中使用JUnit @Rule(例如TemporaryFolder) [英] Using JUnit @Rule with ScalaTest (e.g. TemporaryFolder)
问题描述
我希望能够使用JUnit规则,例如TemporaryFolder
或我们已经内部开发的其他TestRule
.
最好的方法是什么?我知道JUnitSuite,但它似乎没有使用@Rule
批注.
我仍然想使用其他ScalaTest套件.
I would like to be able to use JUnit rules such as TemporaryFolder
or other TestRule
s we have already developed in-house.
What is the best method to accomplish that? I'm aware of JUnitSuite but it doesn't seem to pick up the @Rule
annotation.
I would like to use a different ScalaTest suite anyway.
所以我的问题是:
- ScalaTest诉讼是否支持JUnit规则?
- 如果没有,是否存在可以使用Junit
TestRule
的图书馆? - 如果没有,如何在Scala测试中使用JUnit
TestRule
? - 或者还有一种更合适的Scala特定方法来完成
TemporaryFolder
的内容,或者例如Stefan Birkner的系统规则提供?
- Are JUnit rules supported by a ScalaTest suit?
- If not, is there a library out there which would make using Junit
TestRule
s possible? - If not, how to use JUnit
TestRule
s in Scala tests? - Or is there a more appropriate Scala-specific approach for acomplishing what
TemporaryFolder
, or, e.g., Stefan Birkner's System Rules provide?
这是我尝试使用JUnitSuite
的方法:
Here's what I tried with JUnitSuite
:
class MyTest extends JUnitSuite {
//@Rule
//val temporaryFolder = new TemporaryFolder() // throws java.lang.Exception: The @Rule 'temporaryFolder' must be public.
@Rule
def temporaryFolder = new TemporaryFolder()
@Test
def test: Unit = {
assert(temporaryFolder.newFile() !== null) // java.lang.IllegalStateException: the temporary folder has not yet been created
}
}
推荐答案
您可以通过创建类型为TemporaryFolder
的成员字段并通过@Rule
函数返回该字段值来解决该问题.
You could solve the problem by creating a member field of type TemporaryFolder
and returning this field value by the @Rule
function.
class MyTest extends JUnitSuite {
val _temporaryFolder = new TemporaryFolder
@Rule
def temporaryFolder = _temporaryFolder
@Test
def test: Unit = {
assert(temporaryFolder.newFile() !== null)
}
}
这篇关于在ScalaTest中使用JUnit @Rule(例如TemporaryFolder)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!