如何在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]
}
我可以这样调用方法
parseValueForJsonKeyWithReturnType[Boolean](jsonNode, key="hours")
parseValueForJsonKeyWithReturnType[String](jsonNode, key="hours")
parseValueForJsonKeyWithReturnType[Long](jsonNode, key="hours")
在测试中,我正在尝试
val parseValueForJsonKeyWithReturnTypeInt = PrivateMethod[Int]('parseValueForJsonKeyWithReturnType)
a[RuntimeException] shouldBe thrownBy (object invokePrivate parseValueForJsonKeyWithReturnType[Int](jsonNode, "total" , None))
以确保它将为不受支持的类型抛出运行时异常
但是我得到这个错误:
error: value parseValueForJsonKeyWithReturnType of type SerializerTest.this.PrivateMethod[Int] does not take type parameters.
如果我尝试不使用类型参数,则构建可以成功,但是会出现非法ArgumentException
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
我在做什么错?语法可能错误。