Scala Mock部分剔除

Dan*_*nix 9 unit-testing scala scalamock

我想将一个带有依赖项的scala类的方法存根.有没有办法使用ScalaMock实现这一目标?

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

class TeamService(val dep1: D1) {

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

  def method2(param: Int) = {
    method1(param) * 2
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

有没有办法实现这个目标?

Hen*_*art 0

你必须嘲笑dep1: D1,这样一切都会顺利进行。模拟“一半”或仅模拟某些方法并不是一个好方法。

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

val mockD1 = mock[D1]
val teamService = new TeamService(mockD1)
(mockD1.magicNumber _).returns(22)
teamService.method2(33).should be(44)
Run Code Online (Sandbox Code Playgroud)