EDIT: after the release of JUnit 4.11, you can now annotate the method with @Rule .
You will use it as:
private TemporaryFolder folder = new TemporaryFolder(); @Rule public TemporaryFolder getFolder() { return folder; }
For earlier versions of JUnit, see the answer below.
-
No, you cannot use this directly from Scala. The field must be open and non-static. From org.junit.Rule :
public @interface Rule: Annotates fields that contain rules. Such a field must be public, not static, and a subtype of TestRule.
You cannot declare public fields in Scala. All fields are private and accessory accessible. See the answer to this question .
In addition, there is already an extension request for junit (still open):
Extend the rules to support @Rule public MethodRule someRule () {return new SomeRule (); }
Another option is to allow non-public fields, but this has already been rejected: Allow @Rule annotation in non-public fields .
So your options are:
- clone junit and implement the first sentence, method and send a transfer request
- Extend the Scala class from the java class that implements @Rule
-
public class ExpectedExceptionTest { @Rule public ExpectedException thrown = ExpectedException.none(); }
and then inheriting from this:
class ExceptionsHappen extends ExpectedExceptionTest { @Test def badInt: Unit = { thrown.expect(classOf[NumberFormatException]) Integer.parseInt("one") } }
which works correctly.
Matthew farwell
source share