Mock partially a class with scalamock
Asked Answered
C

1

4

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.

Culminate answered 19/4, 2019 at 10:49 Comment(0)
C
4

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
}
Crumley answered 19/4, 2019 at 11:3 Comment(2)
Very interesting Idea. I wonder if there is a way that doesn't involve creating a new classCulminate
Sorry, no. I maintain ScalaMock as a project and this is the only way i can recommend at the moment.Crumley

© 2022 - 2024 — McMap. All rights reserved.