2010-11-21 75 views
7

我正在使用ScalaTest测试一些Scala代码。 我目前的代码测试的预期异常喜欢这个如何使用ScalaTest测试预期异常的附加属性

import org.scalatest._ 
import org.scalatest.matchers.ShouldMatchers 

class ImageComparisonTest extends FeatureSpec with ShouldMatchers{ 

    feature("A test can throw an exception") { 

     scenario("when an exception is throw this is expected"){ 
      evaluating { throw new Exception("message") } should produce [Exception] 
     } 
    } 
} 

但我想例外,例如上添加额外的检查我想检查异常消息是否包含某个字符串。

有没有一种“干净”的方式来做到这一点?或者我必须使用try catch块吗?

回答

16

我找到了解决办法

val exception = intercept[SomeException]{ ... code that throws SomeException ... } 
// you can add more assertions based on exception here 
9

你可以做同样的事情与评估......应产生语法,因为喜欢拦截,它返回捕获的异常:

val exception = 
    evaluating { throw new Exception("message") } should produce [Exception] 

然后检查异常。

+0

它的工作原理和我喜欢t他的语法:它符合函数结果的所有“应该”。 – 2013-09-11 03:21:31

+0

'评估'在2.x中被弃用,并在3.x中被删除。弃用文档建议使用'an [Exception] thrownBy'来代替。但是3.0.0-M14返回一个'Assertion':'val ex:Assertion = [Exception] thrownBy {throw new Exception(“boom”)}'。有没有办法找回抛出的'Exception'? – kostja 2015-12-21 12:55:01

2

如果你需要进一步检查预期异常,您可以使用此语法捕捉它:

val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ } 

该表达式返回捕捉到的异常,这样就可以进一步检查它:

thrown.getMessage should equal ("Some message") 

您也可以在一个声明中捕获并检查预期的异常,如下所示:

the [SomeException] thrownBy { 
    // Code that throws SomeException 
} should have message "Some message"