我尝试使用PrivateMethodTester
测试 curried 私有方法(实际上是功能),但可以&#39 ; t弄清楚如何调用它
请考虑使用 curried 方法:
object MyObject {
..
private def curriedAdder(augend: Int)(addend: Int): Int = augend + addend
..
}
以下是编译错误
assert(9, MyObject.invokePrivate(PrivateMethod[Int]('curriedAdder)(2)(7)))
..
[error] /path/to/MyObject.scala:76:80: org.scalatest.PrivateMethodTester.Invocation[Int] does not take parameters
[error] assert(9, MyObject.invokePrivate(PrivateMethod[Int]('curriedAdder)(2)(7)))
[error] ^
..
虽然这个找不到功能
assert(9, MyObject.invokePrivate(PrivateMethod[Int => Int]('curriedAdder)(2))(7))
..
[info] - my-test-name *** FAILED ***
[info] java.lang.IllegalArgumentException: Can't find a private method named: curriedAdder
[info] at org.scalatest.PrivateMethodTester$Invoker.invokePrivate(PrivateMethodTester.scala:247)
..
PrivateMethodTester
测试 curried私有方法?框架版本:
"org.scalatest" %% "scalatest" % "3.0.3" % Test
scalaVersion := "2.11.11"
sbt.version=1.0.3
答案 0 :(得分:3)
以下适用于ScalaTest 3.0.1:
val curriedAdder = PrivateMethod[Int]('curriedAdder)
val actualResult = (MyObject invokePrivate curriedAdder(2, 7))
assert(9 == actualResult)
根据docs:
通过反射
动态调用私有方法
当我听到反射时,我会想到Object.getClass()
,因此调用MyObject.getClass.getDeclaredMethods.foreach(println)
方法显示为
private int example.HelloSpec$MyObject$.curriedAdder(int,int)
所以curriedAdder(int,int)
提示我如何称呼这种咖喱方法。