Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Display exception thrown in "should produce [exception]” in ScalaTest

Tags:

scala

I would like to display the Exception message thrown in scala test.

 " iWillThrowCustomException Method Failure test.   
 " should "Fail, Reason: Reason for failing. " in {
 evaluating {
      iWillThrowCustomException();
   } should produce [CustomException]
}

If CustomExeption will throw different types of messages for differnt inputs , say

(for -ve amount - Amount is less than zero, for chars in amount - Invalid amount),

how to display the message which is thrown in the block, becuase it will through the CustomException and it will show Test Success, but for which senario it has thrown the error

like image 306
Azhar Avatar asked Sep 29 '12 11:09

Azhar


2 Answers

Alternatively you can check out intercept:

val ex = intercept[CustomException] {
    iWillThrowCustomException()
}
ex.getMessage should equal ("My custom message")
like image 178
Tomasz Nurkiewicz Avatar answered Oct 20 '22 16:10

Tomasz Nurkiewicz


evaluating also returns an exception so you can inspect it or print the message. Here is example from the ScalaDoc:

val thrown = evaluating { s.charAt(-1) } should produce [IndexOutOfBoundsException]
thrown.getMessage should equal ("String index out of range: -1")

As far as I know, you can't include exception message in the test name.


What you can do, is to add additional information about test with info():

"iWillThrowCustomException Method Failure test." in {
    val exception = evaluating { iWillThrowCustomException() } should produce [CustomException]
    info("Reason: " + exception.getMessage)
}

This will be shown in the test results as nested message. You can find more info about this in ScalaDoc.

like image 25
tenshi Avatar answered Oct 20 '22 17:10

tenshi