Mock partially a class with scalamock

风流意气都作罢 提交于 2021-01-27 06:31:58

问题


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.


回答1:


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
}


来源:https://stackoverflow.com/questions/55760671/mock-partially-a-class-with-scalamock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!