Search code examples
scalapolymorphismscalamock

How to mock a polymorphic function with manifest in Scalamock?


I am trying to mock a polymorphic function belonging to a trait in scala. The method is parameterized with [T: Manifest]

An minimum working (or failing, should I say) example is the following:

class ScalaMockTest extends FlatSpec with MockFactory {

  trait testObject {
    def parameterizedFunction[T: Manifest](a: T): T
  }

  it should "not fail with scalamock" in {
    val mockObject = mock[testObject]

    (mockObject.parameterizedFunction[Int] _)
      .expects(*)
      .returns(3)

    mockObject.parameterizedFunction[Int](3)
  }
}

Which results in the following error: org.scalamock.function.MockFunction2 cannot be cast to org.scalamock.function.MockFunction1 When I remove change the function definition to def parameterizedFunction[T](a: T): T (without the :Manifest), this error no longer occurs.

How can I get rid of this runtime error, and why is this happening? Unfortunately simply removing the Manifest is not possible because of dependencies in the code that I am actually trying to mock.


Solution

  • A little tweak in the syntax should make it work:

    class ScalaMockTest extends FlatSpec with Matchers with MockFactory {
    
      trait testObject {
        def parameterizedFunction[T: Manifest](a: T): T
      }
    
      "this" should "not fail with scalamock" in {
        val mockObject = mock[testObject]
    
        (mockObject.parameterizedFunction(_ : Int)(_ : Manifest[Int]))
          .expects(*, *)
          .returns(4)
    
        mockObject.parameterizedFunction[Int](3) shouldBe 4
      }
    }
    

    It's covered in the user guide