12

我想存根具有依赖关系的 scala 类的方法之一。有没有办法使用 ScalaMock 来实现这一点?

这是我所拥有的简化示例:

class TeamService(val dep1: D1) {

  def method1(param: Int) = param * dep1.magicNumber()

  def method2(param: Int) = {
    method1(param) * 2
  }
}

在这个例子中,我想模拟method1(). 我的测试看起来像:

val teamService = ??? // creates a stub
(teamService.method1 _).when(33).returns(22)
teamService.method2(33).should be(44)

有没有办法做到这一点?

4

3 回答 3

1

正如其他问题中所建议的,在这里这里,我们可以结合stubfinal。来自ScalaMock 常见问题解答

我可以模拟最终/私有方法或类吗?

这是不支持的,因为使用宏生成的模拟被实现为模拟类型的子类。所以私有和最终方法不能被覆盖

因此,您可以method2在源代码中声明为 final,然后进行测试:

it should "test" in {
  val teamService = stub[TeamService]
  (teamService.method1 _).when(33).returns(22)
  teamService.method2(33) shouldBe 44
}

或者,创建一个新的重写类,将您的方法声明为 final:

it should "test" in {
  class PartFinalTeamService(dep: D1) extends TeamService(dep) {
    override final def method2(param: Int): Int = super.method2(param)
  }

  val teamService = stub[PartFinalTeamService]
  (teamService.method1 _).when(33).returns(22)
  teamService.method2(33) shouldBe 44
}
于 2020-11-05T13:42:28.713 回答
0

你必须嘲笑dep1: D1,所以一切都会好起来的。这不是模拟“一半”或仅模拟某些方法的好方法。

模拟dep1: D1是测试它的正确方法。

val mockD1 = mock[D1]
val teamService = new TeamService(mockD1)
(mockD1.magicNumber _).returns(22)
teamService.method2(33).should be(44)
于 2017-09-19T14:03:44.540 回答
0

method1()您可以在创建对象时覆盖TeamService并使其返回您想要的任何值。

val service = new TeamService(2) {
  override def method1(param: Int): Int = theValueYouWant
}

并使用该service对象来测试您的method2().

于 2021-07-16T05:03:37.823 回答