我想测试以下功能:
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
最佳答案
诀窍是将异常具体化为一个值,幸运的是,这在 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
}
}
它的工作原理是,Try[T]
要么是包裹 T
的 Success
,要么是 Failure
> 包装一个Throwable
。 Try { }
将代码包装在 try
block 中并捕获异常;如果是 NonFatal
异常,则该异常将进入 Failure
。还有其他一些使用 Try
的充分理由(它具有一些很好的组合属性),但这些超出了本答案的范围。
关于scala - 如何使用 Junit 4 和 Scala 测试异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70220053/