2017-01-12 55 views
3

這裏是我的方案如何在mockito中模擬日期?

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) 

我試着插入任何(),anyObject()等任何想法在插什麼?

不過,我不斷收到異常:

.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. 

我們不使用powermocks。

回答

4

您傳遞原始值出現(如錯誤已經提到)。使用匹配代替如下:

import static org.mockito.Mockito.*; 

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

作爲錯誤消息指出:

當使用匹配器,所有參數必須由匹配器來提供。

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