使用 PrivateMethodTester 测试采用泛型类型的私有方法

Nit*_*ndy 6 scala private-methods scalatest

如何在 Scala 中使用 privateMethodTester 测试采用泛型类型的私有方法?

假设我有以下方法:

private def parseValueForJsonKeyWithReturnType[A: TypeTag](
   node: JsonNode, 
   key: String, 
   defaultValue: Option[A] = None): A = {

    val parsedValue = Option(node.get(key)).map(value => { 
      typeOf[A] match {
         case t if t =:= typeOf[String] =>
           value.textValue()
         case t if t =:= typeOf[Double] =>
           value.asDouble()
         case t if t =:= typeOf[Long] =>
           value.asLong()
         case _ => throw new RuntimeException(s"Doesn't support conversion to [type=${typeOf[A]}] for [key=${key}]")
       }
    })

    parsedValue.getOrElse(defaultValue.get).asInstanceOf[A]
  }
Run Code Online (Sandbox Code Playgroud)

我可以像这样调用方法

parseValueForJsonKeyWithReturnType[Boolean](jsonNode, key="hours")
parseValueForJsonKeyWithReturnType[String](jsonNode, key="hours")
parseValueForJsonKeyWithReturnType[Long](jsonNode, key="hours")
Run Code Online (Sandbox Code Playgroud)

在测试中,我正在尝试做

val parseValueForJsonKeyWithReturnTypeInt = PrivateMethod[Int]('parseValueForJsonKeyWithReturnType)
a[RuntimeException] shouldBe thrownBy (object invokePrivate parseValueForJsonKeyWithReturnType[Int](jsonNode, "total" , None))
Run Code Online (Sandbox Code Playgroud)

确保它会为不受支持的类型抛出运行时异常

但我收到此错误:

error: value parseValueForJsonKeyWithReturnType of type SerializerTest.this.PrivateMethod[Int] does not take type parameters.
Run Code Online (Sandbox Code Playgroud)

如果我尝试不使用类型参数,构建成功但我得到了非法参数异常

Expected exception java.lang.RuntimeException to be thrown, but java.lang.IllegalArgumentException was thrown. 

Cause: java.lang.IllegalArgumentException: Can't find a private method named: parseValueForJsonKeyWithReturnType
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?可能是语法错误。

Den*_*vac 0

我在 Scala 2.13 和 ScalaTest 3.2.14 上遇到了同样的问题“找不到名为的私有方法”。于是我走进了Scastie,为GitHub问题做了一个例子。但它确实有效!

我的代码中唯一没有添加到此测试中的是对象扩展类,如下所示:

class WithPrivate
object WithPrivate extends WithPrivate
Run Code Online (Sandbox Code Playgroud)

当我仅使用object SomePrivateMethods私有方法进行测试时 - ScalaTest 以所有可能的方式找到私有方法:

class WithPrivate
object WithPrivate extends WithPrivate
Run Code Online (Sandbox Code Playgroud)

https://scastie.scala-lang.org/0eQtkQNzTNm5BNhDEIlIng

因此,如果您遇到此类问题 - 检查您是否正在测试对象或类。