0

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.

RvdV
  • 406
  • 3
  • 10

1 Answers1

1

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

Feyyaz
  • 3,147
  • 4
  • 35
  • 50
  • I stumbled across that link previously but wasn't able to piece this together myself, thanks! What I don't fully understand is why the `.expects` is now a function with two parameters. What should is actually being passed to the function where we match `*,*`? – RvdV Aug 23 '19 at 07:14