I'm trying to simulate the expected exception behavior of common testing frameworks (e.g. JUnit or TestNG).
Here's what I could come up with so far (working):
trait ExpectAsserts
{
self : {
def fail (message : String)
def success (message : String)
} =>
def expect[T](exceptionClass : Class[T])(test : => Unit)
{
try
{
test
fail("exception not thrown")
}
catch
{
case expected : T => success("got exception " + expected)
case other : Exception => fail("expected "+ exceptionClass + " but " + other + " thrown instead.")
}
}
}
object Main extends ExpectAsserts
{
def main (args : Array[String])
{
expect(classOf[ArithmeticException])
{
throw new IllegalArgumentException // this should print an error message.
}
}
def fail (s : String)
{
System.err.println(s)
}
def success(s : String)
{
System.out.println(s)
}
}
The snippet has a main
method that exercises the code. My problem is that the exception thrown enters in the first pattern matching statement:
case expected : T
Although I'm actually saying that the exception has to be of type T
, which would be IllegalArgumentException
.
Any ideas?
Compile with -unchecked
and you'll see a warning that the type test expected: T
will always return true, thanks to type erasure.
scala> def foo[T](a: Any) = a match {
| case _: T => "always will match!"
| }
<console>:22: warning: abstract type T in type pattern T is unchecked since it is eliminated by erasure
case _: T => "always will match!"
^
foo: [T](a: Any)java.lang.String
scala> foo[String](0)
res3: java.lang.String = always will match!
Seeing as you have the class passed in you can use Class#isInstance
instead. In your code, that would look like:
case expected if clazz.isInstance(expected) => success("got exception " + expected)
In a self contained example. Here we pass a Manifest[T]
implicitly, which is a way to get the compiler to pass an extra parameter to obtain the information that type erasure threw away:
scala> def foo[T: ClassManifest](a: Any) = manifest[T].erasure.isInstance(a)
foo: [T](a: Any)(implicit evidence$1: Manifest[T])Boolean
scala> foo[String](new {}) // compiler passes Manifest[String] here
res4: Boolean = false
scala> foo[String]("")
res5: Boolean = true
Further reading:
- How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?
- https://stackoverflow.com/questions/1332574/common-programming-mistakes-for-scala-developers-to-avoid/1338119#1338119
- What is a Manifest in Scala and when do you need it?
- Specs2 Exception Matchers