views:

847

answers:

4

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
+6  A: 

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
}
Tristan Juricek
Yowzer... a case where scala is *less* expressive than java?
skaffman
Yeah, annotations are probably the one area I don't like the language. There is this "if it's called value..." implicit rule, but, meh, not a real fan. Ah well.
Tristan Juricek
+5  A: 

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)
Jay Conrod
That's just saved me from a world of grief. Thx
Brian Agnew
In my case it didn't work until I changed the import statement from import junit.framework.Test import org.junit.Test (which seems not to make any difference under java)
Artur Gajowy
A: 

You can also try specs with:

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

Eric.

A: 

You could also write your own helper method

def shouldThrow[E<:Throwable](f: =>Unit) {
    try {
        f
        fail("should have thrown an Exception")
    } catch {
        case e:E => ()
        case e => throw e
    }
}
Kim