升级到最新版本后:org.specs2.execute.Failure required:T

时间:2014-04-17 11:53:30

标签: scala

将我的scala升级到最新版本后,我收到了错误:

  

类型不匹配;发现:org.specs2.execute.Failure required:T

我的代码:

  def shouldThrow[T <: Exception](exClazz: Class[T])(body: => Unit): T = {
    try {
      body
    } catch {
      case e: Throwable =>
        if (e.getClass == exClazz) return e.asInstanceOf[T]
        val failure = new Failure("Expected %s but got %s".format(exClazz, e.getClass), "", new Exception().getStackTrace.toList, org.specs2.execute.NoDetails())                                                 
        val rethrown = new FailureException(failure)
        rethrown.initCause(e)
        throw rethrown

    }
    failure("Exception expected, but has not been thrown")
  } 

我在最后一行failure("...")

收到此错误

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

可变规范中的

failure过去没有返回类型,然后返回类型为Nothing。这已被修复为返回Failure并且与非可变规范更加一致。

但是,您的代码中不需要failure,因为有例外匹配器(请参阅“例外”标签here),您可以写:

body must throwAn[IllegalArgumentException]

答案 1 :(得分:1)

如消息所示,方法failure返回Failure,但您告诉编译器要返回T。您可以在最后一行(failure可能曾经做过)中抛出异常。您还可以使用Class[T]手动传递ClassTag

def shouldThrow[T <: Exception](body: => Unit)(implicit ct: ClassTag[T]): T = {
  ... // as before
  case e: Throwable =>
    val exClass = ct.runtimeClass
    ... // as before
}

// usage
shouldThrow[IOException] {
  // body
}