15

我正在使用 mockito 并试图模拟一个 scala 对象。

object Sample { }
//test
class SomeTest extends Specification with ScalaTest with Mockito {
    "mocking should succeed" in {
        val mockedSample = mock[Sample]
     }
}

这给了我两个编译错误。

error: Not found type Sample
error: could not find implicit value for parameter m:
scala.reflect.ClassManifest[<error>]

如果我将 Sample 从对象更改为类,它就可以工作。是否可以用 mockito 模拟 scala 对象?如果是怎么办?

4

4 回答 4

15

As written, your Sample is a pure singleton. Its type is its own and there is only one member of that type, period. Scala objects can extend another class (possibly abstract, if it supplies the necessary definitions to make it a concrete) and traits. Doing that gives it a type identity that includes those ancestors.

I don't know what Mockito is really doing, but to my mind, what you're asking for is strictly at odds with what a Scala object is.

于 2010-08-26T14:54:48.760 回答
10

请记住,如果将它们提升为函数,则可以模拟an的方法。object

case class Person(name: String)
object Person {
  def listToJson(lp: List[Person]) = "some actual implementation"
}

class ClassUnderTest(listToJson: (List[Person]) => String = Person.listToJson(_)) {
  def testIt(lp: List[Person]) = listToJson(lp)
}

import org.specs._
import org.specs.mock.Mockito
import org.mockito.Matchers._  

class ASpec extends Specification with Mockito {
  "a thing" should {
    "do whatever" in {
      val m = mock[(List[Person]) => String]
      val subject = new ClassUnderTest(m)
      m(Nil) returns "mocked!"
      subject.testIt(Nil) must_== "mocked! (this will fail on purpose)"
    }
  }
}

在这里,我不是在嘲笑对象 Person,而是在嘲笑对象上的方法(这可能是 OP 的意图)。

测试结果显示了 mocking 工作:

[info] == ASpec ==
[error] x a thing should
[error]   x do whatever
[error]     'mocked![]' is not equal to 'mocked![ (this will fail on purpose)]' (ASpec.scala:21)
[info] == ASpec ==

同时,生产时的使用ClassUnderTest只是new ClassUnderTest因为注入的函数是默认参数。

于 2011-02-02T11:50:23.580 回答
8

由于 mockito-scala 的 1.16.0 版本可以模拟 Scala ,您可以在此处object查看文档,但这是它的外观示例。

object FooObject {
 def simpleMethod: String = "not mocked!"
}

"mock" should {
 "stub an object method" in {
   FooObject.simpleMethod shouldBe "not mocked!"

   withObjectMocked[FooObject.type] {
     FooObject.simpleMethod returns "mocked!"
     //or
     when(FooObject.simpleMethod) thenReturn "mocked!"

     FooObject.simpleMethod shouldBe "mocked!"
   }

   FooObject.simpleMethod shouldBe "not mocked!"
 }
}
于 2020-09-27T21:20:24.050 回答
7

我最近发布了ScalaMock,这是一个 Scala 的模拟库,除其他外,它可以模拟单例(和伴侣)对象。

于 2011-12-27T00:01:53.440 回答