我有以下的Scala函数:
def throwError(spark: SparkSession,df:DataFrame): Unit = {
import spark.implicits._
throw new IllegalArgumentException(s"Illegal arguments")
val predictionAndLabels = df.select("prediction", "label").map {
case Row(prediction: Double, label: Double) => (prediction, label)
case other => throw new IllegalArgumentException(s"Illegal arguments")
}
predictionAndLabels.show()
}
我想测试上述函数抛出的异常,但我的测试失败了。
"Testing" should "throw error for datetype" in withSparkSession {
spark => {
// Creating a dataframe
val someData = Seq(
Row(8, Date.valueOf("2016-09-30")),
Row(9, Date.valueOf("2017-09-30")),
Row(10, Date.valueOf("2018-09-30"))
)
val someSchema = List(
StructField("prediction", IntegerType, true),
StructField("label", DateType , true)
)
val someDF = spark.createDataFrame(
spark.sparkContext.parallelize(someData),
StructType(someSchema)
)
// Testing exception
val caught = intercept[IllegalArgumentException] {
throwError(spark,someDF)
}
assert(caught.getMessage.contains("Illegal arguments"))
}
}
如果我将throw new IllegalArgumentException(s"Illegal arguments")
移动到映射函数调用外面,测试就会通过。
如何测试'throwError'函数抛出的异常?