Scalatest, cannot call invokePrivate

别说谁变了你拦得住时间么 提交于 2019-12-25 03:26:15

问题


I wanted to test a private method in Scala, and found that Scalatest's PrivateMethodTester does what I need. But there seems to be an import problem.

import org.scalatest._

//Alternatively, I tried 
//import org.scalatest.PrivateMethodTester
//import org.scalatest.FlatSpec

"calculateCutoffCriteria" should "give mu -2sigma, mu - sigma, mu + sigma, mu+2sigma as bounds" in {
      val testData = List(-1, -1, 0, 1, 1)
      val expected = (-2, -1, 1, 2)
      val thePrivateMethod = PrivateMethodTester.PrivateMethod[Study]('calculateCutoffCriteria)
      val actual = Study invokePrivate thePrivateMethod(testData)

      assert(actual === expected)
    }

For some reason, I cannot just call PrivateMethod[Study], I have to specify PrivateMethodTester.PrivateMethod[Study]. And invokePrivate doesn't work at all, the whole test doesn't compile with the error that invokePrivate is not a member of the object Study.

My project references scalatest_2.10.-2.1.0.jar, and all the other tests (which don't use PrivateMethodTester) run just like they should. What's the problem here?


回答1:


I've had this problem before when I forgot to extend my test class with the org.scalatest.PrivateMethodTester trait. The PrivateMethodTester is what gives you your invokePrivate method. Give that a shot and see if that helps at all.

import org.scalatest.PrivateMethodTester

class TestSomething extends FlatSpec with PrivateMethodTester {
  "calculateCutoffCriteria" should 
    "give mu -2sigma, mu - sigma, mu + sigma, mu+2sigma as bounds" in {
      val testData = List(-1, -1, 0, 1, 1)
      val expected = (-2, -1, 1, 2)
      val thePrivateMethod = PrivateMethodTester.PrivateMethod[Study]('calculateCutoffCriteria)
      val actual = Study invokePrivate thePrivateMethod(testData)

      assert(actual === expected)
    }
}


来源:https://stackoverflow.com/questions/24571260/scalatest-cannot-call-invokeprivate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!