Scala 无法正确地存根具有实例化新日期的参数的方法

Scala 无法正确地存根具有实例化新日期的参数的方法,scala,mockito,stub,Scala,Mockito,Stub,我正在处理一个scala项目,在我的单元测试中,我必须存根一个以日期作为参数的方法(在调用该方法时,该日期是实例化的),而我无法单独存根它 然而,我通过这篇文章找到了转机 但我想知道是否有更好的方法来做到这一点,因为我发现这个解决方案不是很令人满意 以下是我尝试存根的代码: def foo(): Future[JsonObject] ={ [...] for { a <- b.bar(arg,atDate = Some(Date.from(Inst

我正在处理一个scala项目,在我的单元测试中,我必须存根一个以日期作为参数的方法(在调用该方法时,该日期是实例化的),而我无法单独存根它

然而,我通过这篇文章找到了转机 但我想知道是否有更好的方法来做到这一点,因为我发现这个解决方案不是很令人满意

以下是我尝试存根的代码:

def foo(): Future[JsonObject] ={
 [...]
        for {
            a <- b.bar(arg,atDate = Some(Date.from(Instant.now())))
        } yield a
    }
这无法解析,因此我必须将其更改为:

val b = mock[B]
 when(b.bar(arg, _:Option[Date])).thenReturn({ d:Date => Future.successful(List())})
当我运行它时,我有以下错误:

when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

也许我在错误消息中遗漏了什么,但我觉得它没有帮助。 有没有办法告诉存根取日期的任何值? 另外,尽管函数的返回类型是Future[List[a]],为什么还需要将函数放入return部分


提前感谢

您必须使用
任何
匹配器,因此您的代码看起来像(这里我假设
arg
是测试代码中其他地方定义的变量)

现在这有点冗长,所以如果升级到mockito scala并使用惯用语法,它看起来会像

b.bar(arg, *) returns Future.successful(List())
如果你有/使用猫,你甚至可以这样做

b.bar(arg, *) returnsF List()

有关更多信息,请查看文档

,顺便说一句,可怕的
java.util.Date
类在几年前被JSR 310中定义的现代java.time类所取代。具体来说,替换为
java.time.Instant
。您可以通过添加到旧类中的新方法进行转换。
b.bar(arg, *) returns Future.successful(List())
b.bar(arg, *) returnsF List()