Search code examples
scalaunit-testingmockingscalamock

Scala Mock Syntax (class _).expects meaning?


New to Scala, have searched far and wide for clarification on some ScalaMock syntax. As per this guide, I keep seeing the following general testing pattern:

(myClass.myMethod _).expects()

What exactly is happening here? What function does the class/method/space/underscore serve? How does the compiler treat this?


Solution

  • The appended _ forces the conversion of a method into a function.

    To understand why this is necessary, let's try to re-build a tiny piece of Scalamock, namely the expects method. The expects method seems to be invoked on methods of mocked objects. But methods / functions do not have an expects method to begin with. Therefore, we have to use the "pimp my library"-pattern to attach the method expects to functions. We could do something like this:

    implicit class ExpectsOp[A, B](f: A => B) {
      def expects(a: A): Unit = println("it compiles, ship it...")
    }
    

    Now let's define a class Bar with method baz:

    class Bar {
      def baz(i: Int): Int = i * i
    }
    

    and also an instance of Bar:

    val bar = new Bar
    

    Let's see what happens if you try to invoke expects on bar.baz:

    (bar.baz).expects(42)
    

    error: missing argument list for method baz in class Bar Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing baz _ or baz(_) instead of baz.

    So, it doesn't work without explicit conversion into a function, and we have to enforce this conversion by appending an _:

    (bar.baz _).expects(42) // prints: "it compiles, ship it..."