Search code examples
scalamockingscalatestspy

Object method mocking or spying for unit testing in Scala


Is there a way to mock or spy on methods in a Scala object?

object Object {

  def fun(value: String) = println(value)

  def main(args: Array[String]): Unit = {
    fun("executed")
    sys.exit(0)
  }
}

I would like to do something like:

spy(Object.fun)

I looked at ScalaMock, EasyMock, JMock and Mockito but couldn't really figure it out.


Solution

  • A better approach would be not to use a Scala object for this. It isn't testable.

    Like in java you should avoid using Static as it can't be relaced with a mock.

    If you want to have one instance of the class you can instatiate it once in an object