scala - thenReturn 重载方法有替代方法 - 如何解决?
问题描述
我在一个类中有一个函数,例如:
def saveToken(token: Token, ttl: Instant, client: Client, partner: Partner, info: Info): Future[EitherErrorsOr[Done]]
并且EitherErrorsOr
是:
type EitherErrorsOr[A] = scala.Either[Errors, A]
Errors
是我们的内部Errors
类
当我尝试saveToken
如下模拟时:
when(
mockService.saveToken(
any(), any(), any(), any(), any()
)
).thenReturn(Right(NoOpVal).toFut)
然后我收到一个错误,例如:
overloaded method value thenReturn with alternatives:
(x$1: scala.concurrent.Future[EitherErrorsOr[Done]],x$2: scala.concurrent.Future[EitherErrorsOr[Done]]*)org.mockito.stubbing.OngoingStubbing[scala.concurrent.Future[EitherErrorsOr[Done]]] <and>
(x$1: scala.concurrent.Future[EitherErrorsOr[Done]])org.mockito.stubbing.OngoingStubbing[scala.concurrent.Future[EitherErrorsOr[Done]]]
cannot be applied to (scala.concurrent.Future[scala.util.Right[Nothing,NoOp]])
).thenReturn(Right(NoOpVal).toFut)
为什么会thenReturn
想出这么多替代方案?
注意:
Done
是我们的内部类,表示操作完成,
toFut
转换为Future
对象,NoOpVal
只是为了测试目的而创建的某种类型
解决方案
您遇到的问题在于返回类型。该方法的返回类型是Future[EitherErrorsOr[Done]]
,即Future[Either[Errors, Done]]
。
现在我们来分析Right(NoOpVal).toFut
. 的实现Right
是:
final case class Right[+A, +B](b: B) extends Either[A, B] {
def isLeft = false
def isRight = true
}
让我们假设它NoOpVal
是 type A
,当调用时Right(NoOpVal)
你会得到一个 type 的实例Right[Nothing, A]
,因为你没有提供第一个泛型给Right
.
Right[Nothing, A]
不能铸造成Future[EitherErrorsOr[Done]]
.
你怎么解决这个问题?简单做:
when(mockService.saveToken(any(), any(), any(), any(), any()))
.thenReturn(Right[Errors, Done](NoOpVal).toFut)
并确保NoOpVal
扩展Done
。
推荐阅读
- r - 无法弄清楚为什么正则表达式组在 str_match 中不起作用
- regex - JMeter 中的正则表达式
- python - 如何加快 AWS Transcribe 的处理时间?
- python - 使用 Beautiful soup 抓取数据后如何注入弹性搜索
- machine-learning - 使用随机训练/测试集进行分类的模型选择
- python - 无法使用 pyuic4 命令将 .ui 转换为 .py
- java - java.lang.OutOfMemoryError: Java heap space error,while parsing 5mb data through Stax parser in intellij idea
- arrays - 使用 jq 将带有数组的 tsv 转换为 JSON
- artifactory - 无法使用 jfrog cli 从工件下载符号链接
- c# - MVC 将值/参数从控制器传递到视图