scala - 如何使用 Junit 4 和 Scala 测试异常?

标签 scala apache-spark junit

我想测试以下功能:

   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] 要么是包裹 TSuccess,要么是 Failure > 包装一个ThrowableTry { } 将代码包装在 try block 中并捕获异常;如果是 NonFatal 异常,则该异常将进入 Failure。还有其他一些使用 Try 的充分理由(它具有一些很好的组合属性),但这些超出了本答案的范围。

关于scala - 如何使用 Junit 4 和 Scala 测试异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70220053/

相关文章:

scala - 如何对 List[Int] 对象进行排序?

scala - Scala 中的列表未更新

scala - 为什么 Scala 库避免动态绑定(bind)?

scala - 如何使用 scala/breeze 读取 hdf5 矩阵?

sql - 在 Pyspark 数据框上查找迄今为止的月份和月份

csv - Spark读取多个CSV文件,每个文件一个分区

java - 在 Espresso 测试中断言 ProgressBar 的进度

java - MockMvc测试: model() and hasItem() methods are undefined

excel - Spark : Unexpected end of input stream

java - 如何使用 EasyMock 从模拟接口(interface)调用方法