Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Mock partial stubbing

I'd like to stub one of the methods of a scala class with dependencies. Is there a way to achieve this using ScalaMock?

Here is a simplified example of what I have:

class TeamService(val dep1: D1) {

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

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

In this example I'd like to mock method1(). My test would look like:

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

Is there a way to achieve this?

like image 874
Danix Avatar asked Jan 26 '16 14:01

Danix


1 Answers

As suggested in other questions, here and here, we can combine stub with final. From ScalaMock FAQ:

Can I mock final / private methods or classes?

This is not supported, as mocks generated with macros are implemented as subclasses of the type to mock. So private and final methods cannot be overridden

So you can either declare method2 in your source code as final, and then test:

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

Or, create a new overriding class that declares your method as 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
}
like image 103
Tomer Shetah Avatar answered Nov 03 '22 21:11

Tomer Shetah