Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JUnit ExpectedException in Scala?

I'd like to be able to use JUnit 4.7's ExpectedException @Rule in Scala. However, it doesn't seem to catch anything:

import org.junit._

class ExceptionsHappen {

  @Rule 
  def thrown = rules.ExpectedException.none

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

This still fails with a NumberFormatException.

like image 231
Jay Hacker Avatar asked Sep 08 '11 17:09

Jay Hacker


1 Answers

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")
  }
}
like image 178
lmm Avatar answered Oct 07 '22 11:10

lmm