4

我尝试在我的应用程序中使用 Scalamock 模拟,但我想模拟的是一个带有参数的类。我看到了 scalamock 文档,他们说要模拟类,我必须导入org.scalamock.annotation.mock才能使用某些功能。我的参考是 scalatest docs

“注释”似乎不存在......

我的 sbt 依赖项:

"org.scalamock" % "scalamock-scalatest-support_2.10" % "3.0.1" % "test"
"org.scalamock" % "scalamock-core_2.10" % "3.0.1"

我想我忘记了一个图书馆,但我不知道它是什么..

编辑 :

测试代码:

import org.scalatest.FlatSpec
import org.scalamock.scalatest.MockFactory

class AuthenticationServiceTest extends FlatSpec with MockFactory
{
    "A user" should " be authenticated" in
    {
      val user = mock[User]
      val tenant = mock[Tenant]
      inSequence {
        (authenticate(tenant, user) _).expects.returning(true)
      }

      assert(authenticate(tenant, user))
    }
}

课程:

class User (
  val username    : String,
  var password    : String,
  var firstname   : String,
  var lastname    : String,
  var isActivated : Boolean,
  val tenantId    : TenantId
             )
{}

class Tenant (
  val tenantId    : TenantId,
  val companyName : String,
  var fullAddress : String,
  var email       : String,
  var phone       : String,
  var isActivated : Boolean
               )
{}

测试方法:

def authenticate(tenant: Tenant, user: User): Boolean = { 
//code... 
}

错误 :

[error] Unspecified value parameters username, password, firstname, ...
[error]       val user = mock[User]
[error]                      ^
[error] one error found
[error] (test:compile) Compilation failed
[error] Total time: 9 s, completed 17 oct. 2013 09:16:18
4

1 回答 1

2

您可能阅读了依赖ScalaMock Compiler 插件的生成模拟部分,并且您不依赖它。

在我看来没关系,因为你不需要这个编译器插件来使用 scala mock。要将 scala mock 与scala test一起使用,您可以mock使用org.scalamock.scalatest.MockFactory. 请参阅下面的简单测试与导入:

import org.scalatest.FreeSpec
import org.scalamock.scalatest.MockFactory

class MySpec extends FreeSpec with MockFactory {

  class C {
    def method: String = "ABC"
  }

  abstract class AC {
    def method: String
  }

  trait T {
    def method: String
  }

  trait M[A] {
    def method: A
  }

  "You don't need to create real objects, you can mock" - {
    "class" in {
      val m = mock[C]
      inSequence {
        (m.method _).expects.returning("X")
      }
      assert(m.method === "X")
    }
    "abstract class" in {
      val m = mock[AC]
      inSequence {
        (m.method _).expects.returning("X")
      }
      assert(m.method === "X")
    }
    "trait" in {
      val m = mock[T]
      inSequence {
        (m.method _).expects.returning("X")
      }
      assert(m.method === "X")
    }
    "trait parametrized by type" in {
      val m = mock[M[String]]
      inSequence {
        (m.method _).expects.returning("X")
      }
      assert(m.method === "X")
    }
  }
}
于 2013-10-16T21:47:56.070 回答