我有以下要測驗的功能:
def filterFoo(FooColumnName: String, Foo: Seq[Any]): DataFrame = {
/* validate input parameters */
require(Option(FooColumnName).isDefined)
require(Option(Foo).isDefined)
require(df.columns.contains(FooColumnName))
df.filter(col(FooColumnName).isin(Foo:_*))
我撰寫了以下測驗:
@Test(expected = classOf[IllegalArgumentException])
def testFilterFoorWrongColumnName(): Unit ={
val df = data.toDF(columns:_*)
df.filterFoo(FooColumnName = "foo", Foo = competitors)
}
如果 FooColumnName 在資料框中不存在,它將拋出 IllegalArgumentException。我收到此例外,但因此未能通過測驗。運行測驗時出現此錯誤:
java.lang.IllegalArgumentException: requirement failed
uj5u.com熱心網友回復:
訣竅是將例外具體化為一個值,值得慶幸的是,這在 Scala 中非常慣用。 scala.util.Try位于標準庫中,對此特別有用:
import scala.util.{ Failure, Success, Try }
@Test(expected = classOf[IllegalArgumentException])
def testFilterFoorWrongColumnName(): Unit ={
val df = data.toDF(columns:_*)
val attempt = Try { // note the capital T, this is not the keyword try...
df.filterFoo(FooColumnName = "foo", Foo = competitors)
}
// apologies, I don't know JUnit at all...
attempt match {
case _: Success =>
failTheTest // should have been a failure
case Failure(ex) => // ex is the thrown exception
// can check that the exception is an IllegalArgumentException or whatever
doChecksOnException
}
}
它的作業原理是 aTry[T]是Success包裝 aT或Failure包裝 a Throwable。 Try { }將代碼包裝在一個try塊中并捕獲例外;如果是NonFatal例外,則該例外進入Failure. 還有其他Try一些很好的使用理由(它具有一些很好的組合屬性),但這些超出了本答案的范圍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377876.html
