views:

84

answers:

1

I am using mockito and trying to mock a scala object.

object Sample { }
//test
class SomeTest extends Specification with ScalaTest with Mockito {
    "mocking should succeed" in {
        val mockedSample = mock[Sample]
     }
}
Give me 2 compilation errors.
error: Not found type Sample
error: could not find implicit value for parameter m: scala.reflect.ClassManifest[<error>]

If I change Sample from object to class it works. Is is possible to mock scala objects with mockito? if yes how?

+6  A: 

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.

Randall Schulz
Definitely agree here. You might be able to try mock[Sample.type], but I doubt it would work in practice. I'd recommend having Sample extend some interface trait and mock it out that way.The big issue is that if you want to inject your mock in place of the singleton Sample, you'll have to do some nice, evil, fun reflective magic. If you're interested, We can post that.
jsuereth
I was looking at the Mockito source code the other day to answer a related question (which for some reason I cannot find, now) and I seem to recall seeing one of the "mock" generators that just returns a specific value rather than trying to generate alternates / variants.
Randall Schulz