How can I use MockitoSugar to mock an object (singleton) method?

元气小坏坏 提交于 2019-12-23 04:32:26

问题


Is there a way in scala to use MockitoSugar in order to mock a method of an object that is a scala singleton?


回答1:


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.




回答2:


Mockito won't help with objects, but you can try to use ScalaMock instead.



来源:https://stackoverflow.com/questions/17702237/how-can-i-use-mockitosugar-to-mock-an-object-singleton-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!