0

I Have a class called SomeClass in scala & SomeClass object. now I need to Mock the OtherClass which is instantiated in SomeClass object

    class SomeClass {
            import SomeClass._
            def doSomething(param1:Map[String,String],param2:Int) :String{ 
            val returnForSomething= instanse.otherClassFuntion(param2)
        .....
         }

            def doSomethingElse(param:Int) :Map[String,String]{ 
           val returnForSometingElse= instanse.otherClassFuntion(param)
        ....
        }

    object SomeClass{
        lazy val instance =new OtherClass
     }

I'm using scala mockito sugar to mock The other class tried spying on OtherClass but when I call

 val instance = spy(new OtherClass)

but how to pass this instance when the object calls new instance in SomeClass object

Kalpish Singhal
  • 382
  • 1
  • 3
  • 20

1 Answers1

1

You cannot mock values in objects. They don't have constructors that would allow you to inject dependencies. They are serving the same purpose as classes with static methods.

If you really need this functionality, you would have to create some sort of setter allowing you to override the instance:

object SomeClass {
  private var _instance = new OtherClass

  def instance = _instance

  // put your package name in []
  private[thispackage] def instance_=(newInstance: OtherClass) = _instance = OtherClass
  // to make it accessible only within thispackage and its subpackages
}

However, considering that:

  • objects are global (just like static methods in Java)
  • global mutable state is almost always bad
  • and so objects (and static methods) should be stateless if you want to write testable code

there is something wrong about this use case. instance should not require mocking, faking or spying. If it does, then it should NOT be used as a global from within SomeClass but rather default value passed through a constructor, that can be replaced:

class SomeClass(instance: OtherClass = SomeClass.instance) {
  ...
}

or something like that.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64