我尝试在Scalamock的应用程序中使用模拟,但是我要模拟的是带有参数的类。我看到了scalamock doc,他们说要模拟类,我必须导入org.scalamock.annotation.mock
才能使用某些功能。 My reference is 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):
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
最佳答案
您可能已经阅读了依赖于的ScalaMock Compiler插件生成的模拟部分,并且您对此没有依赖性。
在我看来,这是可以的,因为您不需要此编译器插件即可使用scala模拟。要将scala模拟与一起使用,可以使用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")
}
}
}