Question

I want to set an expected exception for a JUnit 4 test using Scala. I am current doing something similar to the following:

@Test(expected=classOf[NullPointerException])
def someTest() = {
    // Some test code
}

But I get the following compiler error:

error: wrong number of arguments for constructor Test: ()org.junit.Test
Was it helpful?

Solution

The way scala deals with attributes is a little funky. I think what you're trying to do should be expressed like this:

@Test { val expected = classOf[ NullPointerException] }
def someTest {
    // test code
}

OTHER TIPS

This is looking forward a bit, but the syntax for annotations in 2.8 has changed to be the same as what you originally posted. The syntax Tristan posted is correct in the current stable version, but it gave me errors when I upgraded my project to a nightly 2.8 compiler. I'm guessing this is due to the inclusion of named and default arguments. There is also some discussion on the Scala mailing list. Quoting Lukas Rytz:

Also note that in 2.8.0 the syntax for java annotations will no longer use the name-value pairs but named arguments instead, i.e.

@ann{ val x = 1, val y = 2}  ==>  @ann(x = 1, y = 2)

You can also try specs with:

class mySpec extends SpecificationWithJUnit {
  "this expects an exception" in {
     myCode must throwA[NullPointerException]
  }
}

Eric.

Use ScalaTest and JUnit together and you can do:

import org.scalatest.junit.JUnitSuite
import org.scalatest.junit.ShouldMatchersForJUnit
import org.junit.Test

class ExampleSuite extends JUnitSuite with ShouldMatchersForJUnit {

  @Test def toTest() {
    evaluating { "yo".charAt(-1) } should produce [StringIndexOutOfBoundsException]
  }
}

This works for me (JUnit 4.10, Scala 2.10.2):

@Test(expected = classOf[NullPointerException])
def testFoo() {
    foo(null)
}

Similar to what Tristan suggested, but this syntax actually compiles and works in my project.

Edit: Uh, looking closer, this is exactly what the original question had. Well, I guess having the latest working syntax also in answers doesn't hurt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top