Search code examples
scalascalatestscalamock

How can you mock a method call on a trait with ScalaMock?


Before you point to the documentation, please point out what's wrong with this minimal, failing example:

import org.scalatest.FlatSpec
import org.scalamock.scalatest.proxy.MockFactory

class StubbingTest extends FlatSpec with MockFactory {
  trait Foo {
    def f(x: Int): Int
  }

  "foo" should "stub" in {
    val foo = stub[Foo]

    (foo.f _).when(3).returns(4)

    assert(foo.f(3) == 4)
  }
}

Which results in java.lang.NoSuchMethodException: com.sun.proxy.$Proxy4.mock$f$0() at line 11: (foo.f _).when ...

According to the documentation, this should work. What am I missing here?


Solution

  • I figured it out by pure luck while browsing the Scaladoc:

    Change

    import org.scalamock.scalatest.proxy.MockFactory
    

    to

    import org.scalamock.scalatest.MockFactory
    

    My IDE's Auto-import failed me, but it would have really helped if the ScalaMock documentation examples included proper imports.