使用Scala、ScalaTest和Mocktio模拟Scala特性

使用Scala、ScalaTest和Mocktio模拟Scala特性,scala,mockito,scalatest,Scala,Mockito,Scalatest,无论出于何种原因,Mocktio都不会模仿我在trait中使用的方法,它会调用实际的方法。这是我的测试: "displays the index page" in { val mockAuth = mock[AuthMethods] when(mockAuth.isAllowed(-1, "", "")).thenReturn(true) val controller = new TestController() val result = controller.index().a

无论出于何种原因,Mocktio都不会模仿我在trait中使用的方法,它会调用实际的方法。这是我的测试:

"displays the index page" in {
  val mockAuth = mock[AuthMethods]
  when(mockAuth.isAllowed(-1, "", "")).thenReturn(true)
  val controller = new TestController()
  val result = controller.index().apply(FakeRequest())
  val bodyText = contentAsString(result)
  bodyText must include ("Name")
}
以下是特点和目标:

trait AuthMethods {
  def isAllowed(userID:Long, method:String, controller:String) : Boolean = {
     //do stuff..
  }
object Authorized extends AuthMethods with ActionBuilder [Request] {
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
    if(isAllowed(userID, method, controller) {
       //do some more stuff..
  }
你有没有想过为什么它把实际的方法称为模拟的方法?我使用的是Scala 2.10.4。任何帮助都将不胜感激

我忘了提到,“授权”是一个动作合成,下面是它的使用方式:

  def index = Authorized {
    Ok(html.Stations.index(Stations.retrieveAllStations))
  } 

您已经创建了一个mock实现
mockAuth
,但尚未对其进行任何操作。创建模拟实现不会神奇地导致它替换其他对象。看起来您想要创建一个
Authorized
对象的模拟,并安排TestController使用它。你可能需要在某个地方打破依赖关系


(更新)由于这是在Play框架的上下文中,您可能会发现这很有帮助。它描述了一种与你类似的情况。为了提供模拟实现,似乎您必须更改引用
authorited
对象的方式。

如何获得其
AuthMethods
实现?显示该代码可能有助于我们理解。@DonRoby我添加了它是如何使用授权对象的。我更新了我的问题,以包括授权对象的使用位置。这个答案还适用于这个问题吗?我用一个有用的(我希望)指针更新了我的答案,指向的信息似乎与你的情况相符。