How can I use JUnit ExpectedException in Scala?

To make this work with JUnit 4.11 in Scala, you should meta-annotate your annotation so that the annotation is applied only to the (synthetic) getter method, not the underlying field:

import org.junit._
import scala.annotation.meta.getter

class ExceptionsHappen {

  @(Rule @getter)
  var thrown = rules.ExpectedException.none

  @Test
  def badInt: Unit = {
    thrown.expect(classOf[NumberFormatException])
    Integer.parseInt("one")
  }
}

EDIT: Following the release of JUnit 4.11, you can now annotate a method with @Rule.

You will use it like:

private TemporaryFolder folder = new TemporaryFolder();

@Rule
public TemporaryFolder getFolder() {
    return folder;
}

For earlier versions of JUnit, see the answer below.

--

No, you can't use this directly from Scala. The field needs to be public 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 a public fields in Scala. All fields are private, and made accessible by accessors. See the answer to this question.

As well as this, there is already an enhancement request for junit (still Open):

Extend rules to support @Rule public MethodRule someRule() { return new SomeRule(); }

The other option is that it non-public fields be allowed, but this has already been rejected: Allow @Rule annotation on non-public fields.

So your options are:

  1. clone junit, and implement the first suggestion, the method, and submit a pull request
  2. Extend the Scala class from a java class which implements the @Rule

-

public class ExpectedExceptionTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();
}

and then inheriting from that:

class ExceptionsHappen extends ExpectedExceptionTest {

  @Test
  def badInt: Unit = {
    thrown.expect(classOf[NumberFormatException])
    Integer.parseInt("one")
  }
}

which works correctly.