如何声明expectedException,才能只传递Exception和子类?目前我正在使用 expectedException: Any
。
详细信息。
我有一个像这样调用的测试实用程序方法,
assertExceptionThrown("En-passant should be rejected when the previous move was not a double advance", classOf[UnreachablePositionException] ) {
e.rejectIllegalMove(EnPassant("e5", "d6"))
}
第一个参数列表的第二个参数是classOf[SomeException]。这是测试方法的签名,
// TODO: Restrict expectedException to Exception or subclass
def assertExceptionThrown(assertion: String, expectedException: Any)(b: => Unit) {
我的问题是,如何声明expectedException,以便只传递异常和子类?目前我正在使用 expectedException: Any。
测试特性的完整源代码在这里, https://github.com/janekdb/stair-chess/blob/master/src/test/Test.scala
最佳答案
使用泛型:
def assertExceptionThrown[T <: SomeException](assertion: String, expectedException: Class[T])(b: => Unit)
这表示 expectedException
的类型 T
必须是 SomeException
或其子类。
演示:
class A
class B extends A
def f[T <: A](x: Class[T]) {} // f accepts Class[A] or a Class[subclass of A]
f(classOf[A]) // fine
f(classOf[B]) // fine
f(classOf[Int]) // error: inferred type arguments [Int] do not conform to method f's type parameter bounds [T <: A]
关于scala - 如何将 Scala 方法参数限制为 classOf[Exception] 或 classOf[Exception 的子类型],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9812684/