无法使用实例化新日期的参数正确存根方法

Unable to properly stub a method with an argument instanciating a new Date

我正在做一个 scala 项目,在我的单元测试中,我必须存根一个方法,该方法将日期作为参数(在调用该方法时实例化),但我无法正确地存根

但是,我使用这个 post How to mock new Date() in java using Mockito 找到了转机 但我想知道是否有更好的方法来做到这一点,因为我发现该解决方案不是很令人满意......

这是我尝试存根的代码:

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(Future.successful(List()))

这不解析,所以我必须将其更改为:

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.

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

提前致谢

你必须使用 any 匹配器,所以你的代码看起来像(这里我假设 arg 是在你的测试代码中其他地方定义的变量)

when(b.bar(ArgumentMatchers.eq(arg), ArgumentMatchers.any())).thenReturn(Future.successful(List()))

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

b.bar(arg, *) returns Future.successful(List())

如果你have/use猫,你甚至可以做到

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

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