用 scalamock 部分模拟一个类 [英] Mock partially a class with scalamock

查看:47
本文介绍了用 scalamock 部分模拟一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用两个函数来测试 Cls 类:AB.A 加载一个 DataFrame 并且 B 调用 A 然后执行一些操作并返回一个新的 DataFrame.举个例子:

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
}

使用 Scalamock 如何编写我的测试代码?

With Scalamock how can write my test code ?

我试过了:

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

我希望测试成功通过并且我得到 0 不等于 6 (mytestcase.scala:24)(我知道 scalamock 用模拟替换了所有现有函数,但这不是预期的行为)

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)

我发现这个 answer 引用了这个 concept 在 mockito 中,但我不确定 scalamock 是否支持这种模拟以及为什么不建议这样做.

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.

推荐答案

ScalaMock 不会覆盖/存根 final 方法.因此,您的解决方案可能是创建一个子类,其中部分方法标记为 final:

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
}

这篇关于用 scalamock 部分模拟一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆