模拟一个没有参数但带有隐式参数的方法
Mock a method without arguments but with implicit parameters
abstract trait MyApi {
def getResult()(implicit ec: ExecutionContext): Future[String]
}
以下不有效:
val m = mock[MyApi]
(m.getResult _).expects() returning "..."
它失败了:
java.lang.ClassCastException: org.scalamock.MockFunction1 cannot be cast to org.scalamock.MockFunction0
注: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
中给出的例子
我猜你没有看到正确的例子。查看示例 4 的隐式参数:
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))
在你的例子中,当然,非隐式参数是空的,所以你想要:
(m.getResult()(_: ExecutionContext)).expects(*) returning "..."
只是为了完成案件。如果有人试图用更多的参数做同样的事情,片段如下:
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))
abstract trait MyApi {
def getResult()(implicit ec: ExecutionContext): Future[String]
}
以下不有效:
val m = mock[MyApi]
(m.getResult _).expects() returning "..."
它失败了:
java.lang.ClassCastException: org.scalamock.MockFunction1 cannot be cast to org.scalamock.MockFunction0
注: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
中给出的例子我猜你没有看到正确的例子。查看示例 4 的隐式参数:
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))
在你的例子中,当然,非隐式参数是空的,所以你想要:
(m.getResult()(_: ExecutionContext)).expects(*) returning "..."
只是为了完成案件。如果有人试图用更多的参数做同样的事情,片段如下:
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))