2015-07-04 76 views
0

爲了測試我的代碼拋出預期例外,我使用的語法如下:ScalaTest thrownBy測試異常消息

an [IllegalArgumentException] should be thrownBy(Algorithms.create(degree)) 

有沒有什麼辦法來測試是否拋出異常包含預期的消息,如:

an [IllegalArgumentException(expectedMessage)] should be thrownBy(Algorithms.create(degree)) -- what doesn't compile 

回答

1

Documentation

the [ArithmeticException] thrownBy 1/0 should have message "/ by zero" 

,並使用例如:

the [IllegalArgumentException] thrownBy(Algorithms.create(degree)) should have message expectedMessage 
+2

如何檢查消息的子字符串?將「the ... thrownBy ...」的結果賦值給val,然後使用常規匹配器? –

1

您的檢查消息語法是錯誤的。作爲替代到什麼bjfletcher建議,您也可以使用下面,按照文檔:

  1. 捕獲該異常並將其分配給一個VAL

val thrown = the [IllegalArgumentException] thrownBy Algorithms.create(degree)

  • 使用val檢查其內容。例如爲:
  • thrown.getMessage should equal ("<whatever the message is")

    我個人比較喜歡通過bjfletcher多加介紹了,因爲它是更緊湊的第一選擇。但是捕捉異常本身,給你更多的可能性來檢查它的內容。