2015-07-04 75 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多加介绍了,因为它是更紧凑的第一选择。但是捕捉异常本身,给你更多的可能性来检查它的内容。