Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock date in mockito?

Tags:

java

mockito

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 ?

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.

like image 636
JavaDeveloper Avatar asked Jan 12 '17 05:01

JavaDeveloper


2 Answers

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)
like image 164
rkosegi Avatar answered Nov 11 '22 21:11

rkosegi


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)
like image 24
Robby Cornelissen Avatar answered Nov 11 '22 20:11

Robby Cornelissen