Reputation: 15133
Is there a way in scala to use MockitoSugar
in order to mock a method of an object
that is a scala singleton?
Upvotes: 0
Views: 4841
Reputation: 815
Mockito won't help with object
s, but you can try to use ScalaMock instead.
Upvotes: 0
Reputation: 35463
Your best bet to deal with singletons for mocking is to first do a little rework on the structure of the singleton itself. Use a trait to define the operations and then have the object extend the trait like so:
trait Fooable{
def doFoo:String = "foo"
}
object Foo extends Fooable
Then, in any class that needs the Foo
object, declare it as an input or something that can be set (DI), but decalare it as the trait instead like this:
class MyFooUser(foo:Fooable = Foo){
}
That way by default it uses the object, but when constructing for your tests, you can give it a mocked Fooable
instead. There are a bunch of ways to handle getting the Fooable
into your classes (this is one) and that's not really in scope for this answer. The answer really is about using a trait first to define the methods and then having the object extend that trait and then referring to it as the trait in any class that needs it. That will allow you to mock it effectively.
Upvotes: 7