Search code examples
scalagenericsscalatest

Scala stub class with generics


I am trying to stub a case class which has structure similar to below code.

case class Employee[T](name:T) {
  def greet(str:String):String = {
    "Hi, "+ str + ":" + name
  }

  def farewell(str:String):String = {
    "Bye, "+ str + ":" + name
  }
}

However, when creating a stub like this: val emp = stub[Employee[String]], gives the following error:

type mismatch;
 found   : T
 required: String
  val emp = stub[Employee[String]]

How can i Stub this class.


Solution

  • Stubbing cases classes is usually avoided but assuming you are using ScalaMock try extending it first with some defaults, for example

    class StrEmployee extends Employee[String](null)
    val emp = stub[StrEmployee]
    (emp.greet _).when("aa").returns("bb")
    assert(emp.greet("aa") == "bb")