Search code examples
scalascalamock

Mock partially a class with scalamock


I'm trying to test a class Cls with two functions: A and B. A loads a DataFrame and B calls A then does some operations and returns a new DataFrame. For the sake of example:

class Cls {
    def A(dummy: Int): Int = 5
    def B(): Int = A(7) + 1
}

With Scalamock how can write my test code ?

I tried:

test("test case") {
  val f = stub[Cls]
  f.A _ when 7 returns 5
  assert(f.B() == 6)
}

I expect test passed successfully and I get 0 did not equal 6 (mytestcase.scala:24) (I do understand that that scalamock replaced all existing functions with mock however this is not the intended behavior)

Edit: I found this answer which references this concept in mockito but I'm not sure if scalamock supports this kind of mocking and why it's advised against.


Solution

  • ScalaMock does not override/stub final methods. So your solution could be to create a subclass with parts of the method marked as final:

    import org.scalamock.scalatest.MockFactory
    import org.scalatest.FunSuite
    
    class PartialMockingTest extends FunSuite with MockFactory {
    
      test("test case") {
    
        class PartFinalCls extends Cls {
          override final def B(): Int = super.B()
        }
    
        val f = stub[PartFinalCls]
        f.A _ when 7 returns 5
        assert(f.B() == 6)
      }
    
    }
    
    class Cls {
      def A(dummy: Int): Int = 5
      def B(): Int = A(7) + 1
    }