java 如何在mockito中模拟日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41605553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:59:10  来源:igfitidea点击:

How to mock date in mockito?

javamockito

提问by JavaDeveloper

Here is my scenario

这是我的场景

public int foo(int a) {
   return new Bar().bar(a, new Date());
}

My test:
Bar barObj = mock(Bar.class)
when(barObj.bar(10, ??)).thenReturn(10)

I tried plugging in any(), anyObject() etc. Any idea what to plug in ?

我尝试插入 any()、anyObject() 等。知道要插入什么吗?

However I keep getting exception:

但是我不断收到异常:

.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
3 matchers expected, 1 recorded:


This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

We dont use powermocks.

我们不使用 powermocks。

回答by rkosegi

You pass raw value there (as error already mentioned). Use matcher instead like this:

您在那里传递原始值(正如已经提到的错误)。像这样使用匹配器:

import static org.mockito.Mockito.*;

...
when(barObj.bar(eq(10), any(Date.class))
   .thenReturn(10)

回答by Robby Cornelissen

As the error message states:

正如错误消息所述:

When using matchers, all arguments have to be provided by matchers.

使用匹配器时,所有参数都必须由匹配器提供。

Bar bar = mock(Bar.class)
when(bar.bar(eq(10), anyObject())).thenReturn(10)