Search code examples
scalaunit-testingscalamock

How to mock a method without a parameter list with ScalaMock 5.0.0?


When trying to mock a method declared as

def foo: Int

with

val mock = mock[MyClass]
(mock.foo _).expects().returning(10)

I get an error Error: Methods without a parameter list and by-name params can no longer be converted to functions as `m _`, write a function literal `() => m` instead

There's a tip to write a function literal instead but I don't quite understand how to convert my code into an equivalent function literal.


Solution

  • Nice to see people using ScalaMock 5 already! Our test case in the unit tests looks like this:

    Trait:

    def noParamMethod(): String
    

    related test for it:

    (() => mockedTrait.noParamMethod()).expects().returning("yey")
    

    It's here in the code: https://github.com/paulbutcher/ScalaMock/blob/master/shared/src/test/scala/org/scalamock/test/mockable/TestTrait.scala

    and the test for it: https://github.com/paulbutcher/ScalaMock/blob/22c26174bfb99b403af2be38ab35cabfe58f4c5f/shared/src/test/scala/org/scalamock/test/scalatest/BasicTest.scala#L39

    Worth mentioning that this should only be needed for Scala 2.13 to satisfy compiler changes in that version.