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.
So my questions are:
- 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?
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
}
}
Here is what I came up based on ScalaTest's documentation on fixtures. Still, I would like to know if there is a better solution.
Loan-fixture method
Using stackable mixins with
withFixture(test: NoArgTest)
overrideBeforeAfterEach#beforeEach()
Overriding
withFixture(test: OneArgTest)
Which one do you like the best?
You could solve the problem by creating a member field of type
TemporaryFolder
and returning this field value by the@Rule
function.This worked for me. Based on answer. So annotation will be applied to to the (synthetic) getter method
Just make sure to use junit version >4.11.