How to mock a static method in scala?

783 Views Asked by At

I have a static method in scala and by static method I mean to say that this method is inside an Object named as MyObject. I also have a class named as MyClass where there is a method which calls the method of MyObject internally. I want to write unit test for MyClass and wanted to mock method of MyObject. How can I do this in scala?

class MyClass {

  def callMyObject(): String = MyObject.myMethod()

}

object MyObject {

  def myMethod(): String = "Original method"

}

I wish when I call callMyObject() of MyClass it should then return a mocked value instead of "Original method"

I am trying mockStatic and spy but no help.

1

There are 1 best solutions below

0
On

This code requires a little bit of refactoring to make it testable.

First, make the MyObject extend a trait. Let's say MyGenericObject.

trait MyGenericObject {
    def sayMyName: Unit
}

object MyObject extends MyGenericObject{
    def sayMyName: Unit = println("foo bar") 
}

Then refactor the MyClass to take in myObj: MyGenericObject.

class MyClass(myObj: MyGenericObject) {
    def saySomeonesName: Unit = myObj.sayMyName
}

Now for testing MyClass you can create a new object MyTestObject that will extend MyGenericObject so that we can pass it to MyClass.

object MyTestObject extends MyGenericObject {
    def sayMyName: Unit = println("test bar") 
}

Now for testing.

val myClass = new MyClass(MyObject)
myClass.saySomeonesName
// Output: foo bar

val myTestClass = new MyClass(MyTestObject)
myTestClass.saySomeonesName
// Output: test bar