2012-03-21 44 views
2

如何聲明expectedException,以便只能傳遞Exceptions和Subclass?目前我正在使用expectedException: Any如何將Scala方法參數限制爲classOf [Exception]或classOf [Exception的子類型]

詳情

我有被調用這樣的測試工具的方法,

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:任何。

測試性狀的全部源代碼在這裏, https://github.com/janekdb/stair-chess/blob/master/src/test/Test.scala

回答

10

使用泛型:

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] 
相關問題