Mock a method without arguments but with implicit parameters
Asked Answered
B

2

5
abstract trait MyApi {

  def getResult()(implicit ec: ExecutionContext): Future[String]

}

The following doesn't work:

val m = mock[MyApi]
(m.getResult _).expects() returning "..."

It fails with:

java.lang.ClassCastException: org.scalamock.MockFunction1 cannot be cast to org.scalamock.MockFunction0

Note: the example given in http://scalamock.org/user-guide/advanced_topics/ is only useful if the method has at least one argument. So we can't use the solution as in mocking methods which use ClassTag in scala using scalamock

Barranquilla answered 26/5, 2015 at 19:50 Comment(0)
R
13

You didn't look at the right example, I guess. Look at example 4 for implicit parameters:

class Codec()

trait Memcached {
  def get(key: String)(implicit codec: Codec): Option[Int]
}

val memcachedMock = mock[Memcached]

implicit val codec = new Codec
(memcachedMock.get(_ : String)(_ : Codec)).expects("some_key", *).returning(Some(123))

In your case, of course, the non-implicit params are null, so you want:

(m.getResult()(_: ExecutionContext)).expects(*) returning "..."
Roving answered 26/5, 2015 at 21:20 Comment(1)
The solution is: (m.getResult()(_: ExecutionContext)).expects(*) returning "...", if you update your answer I will accept it.Barranquilla
D
1

Just to complete the cases. If someone tries to do the same with more params the snippet is the following:

trait MemcachedV2 {
   def get(key: String, value: String)(implicit codec: Codec): Option[Int]
}

val memcachedMock2 = mock[MemcachedV2]

(memcachedMock2.get(_, _)(_))
   .expects("some_key","another value", *)
   .returning(Some(123))
Dunois answered 11/1, 2022 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.