Scalamock:无法使用类型参数和多个隐式变量来模拟函数

时间:2017-05-09 16:55:34

标签: scala unit-testing mocking scalatest scalamock

此问题是https://github.com/paulbutcher/ScalaMock/issues/79

中提到的已解决问题的扩展

我有以下特点来模拟:

trait HttpClient{
   def deserialize[T](response: HttpResponse)
                    (implicit um: Unmarshaller[ResponseEntity, T],
                     executionContext: ExecutionContext): Future[T]
}

我试图按如下方式模拟HttpClient

val client = mock[HttpClient]

case class SomeTypeT(name:String, id:Int)
implicit val someTypeTFormat = jsonFormat2(SomeTypeT)   // to be able to marshal and unmarshal from JSON

(httpClient.deserialize[SomeTypeT](_: HttpResponse))
.expects(where {
  (response: HttpResponse) => {
    response.entity == ent
  }
})
.returns(Unmarshal(response.entity).to[SomeTypeT])

当我尝试模拟反序列化函数时会出现问题。如上所述,deserialize方法由类型化参数T和类型HttpResponse的单个参数组成,还有2个在解组响应时使用的隐式参数。

因此,问题是如何使用ScalaMock模拟deserialize函数并在模拟时指定多个隐式参数。这不起作用

// Both UnMarshaller & ExecutionContext are available here as implicits
(httpClient.deserialize[SomeTypeT](_: HttpResponse)(_: Unmarshaller[ResponseEntity, SomeTypeT](_: ExecutionContext))

问题是我无法使用_来指定隐式参数。而且我不知道如何实现这一目标。请帮助如何模拟给定的功能

我使用以下库:

  • scala版本2.11.8
  • scalatest version 3.0.0
  • scalamock版本3.5.0

虽然由于使用了多个_,第二次尝试甚至无法编译,但第一次尝试导致以下异常:

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

1 个答案:

答案 0 :(得分:1)

在GitHub上回答你链接后,你的代码应该是

(httpClient.deserialize[SomeTypeT](_: HttpResponse)(_:  Unmarshaller[ResponseEntity, SomeTypeT], _:ExecutionContext))
.expects(where {
  (response: HttpResponse, _:  Unmarshaller[ResponseEntity, SomeTypeT], _:ExecutionContext) => {
    response.entity == ent
  }
})
.returns(Unmarshal(response.entity).to[SomeTypeT])

即。你明确地将调用中隐式参数的占位符作为第二组参数放在where中作为所有非隐式的附加参数。