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?