6
votes

I have a Scala object and it contains a few utility functions. These functions are called by other functions present in the same object or from other classes/objects. Is it possible to mock this object or the functions so that I can unit test the classes where they are being called.

Example:

object Util {

  def methodA() = { 
    //other code
    methodB() 
    //other code
  }

  def methodB() = { 
    //other code
    methodC() 
    //other code
  }

  def methodC() = { ... }

}

And here I'm calling the object function from another class

class Data {

  //other code

  def call() = {
    //other code
    Util.methodA()
    //other code
  }
}

How can I go about unit testing the function call() of class Data ? In Java I can create a mocked object for Util and set expectations for a call to methodA(), but this is not possible in Scala since no mocking library supports mocking of a Scala object.

1
There are many scala mocking options. See scalatest.org/user_guide/testing_with_mock_objects for example. Any quick search will bring you many options - Assaf Mendelson
Yes I have already seen the link that you have provided, but none of the mocking frameworks mentioned there support mocking of Scala objects. ScalaMock 2 supported mocking of objects but it has been discontinued in ScalaMock 3, which is latest version for Scala 2.11 compiler. - noober

1 Answers

9
votes

The problem in some sense is that you've used a pattern that is similar to a static class in Java. You can't mock static classes, which is why Java patterns often don't favor that approach.

On the other hand, in Scala you can. Make Util extend a trait and implement it.

trait UtilityMethods {
 def methodA()
 def methodB()
}

object Utils extends UtilityMethods {
  def methodA() = {}
  def methodB() = {}
}

And then in your test:

val mockedUtils = mock[UtilityMethods]

(using mockito). Obviously you will have to pass UtilityMethods around your code instead of Utils, just like you would wth an interface in Java.

In general, you can also use implicit scoping to inject functions and thus mock those dependencies without a static-like object approach, but the above is pretty close to Java patterns and should feel pretty comfortable.