Search code examples
scalatestingstubstubbingscalamock

ScalaMock, returns based on a ClassTag


How can I stub a method that use a ClassTag in the implementation ?

class RefsFactory {
  def get[I <: Item : ClassTag]: RefTo[I] = {
    val itemType = implicitly[ClassTag[A]].runtimeClass.asInstanceOf[Class[A]]
    // ...
  }
}

This class is used a lot in our code and I would like to stub it to return others mock regarding the itemType.

val factory = stub[RefsFactory]
val otherType = stub[RefTo[OtherType]]
(factory.get[OneType]) returns RefTo(new OneType())
(factory.get[OtherType]) returns otherType

Thanks


Solution

  • Trying to simplify your problem, the method

    def get[I <: Item : ClassTag]: RefTo[I]
    

    is similar to having a context bound on 0-arity method

    def foo[I: ClassTag]
    

    which is equivalent to method with one implicit argument

    def foo[I](implicit ev: ClassTag[I)
    

    hence considering Methods with implicit parameters we can mock like so

    (myMock.foo[SomeType](_: ClassTag[SomeType])).expects(*).returns(...)