Search code examples
junitmockitopowermockito

Mockito - You cannot use argument matchers outside of verification or stubbing - have tried many things but still no solution


I have the following piece of code:

PowerMockito.mockStatic(DateUtils.class);      
//And this is the line which does the exception - notice it's a static function  
PowerMockito.when(DateUtils.isEqualByDateTime (any(Date.class),any(Date.class)).thenReturn(false);

The class begins with:
@RunWith(PowerMockRunner.class) @PrepareForTest({CM9DateUtils.class,DateUtils.class})

And I get org.Mockito.exceptions.InvalidUseOfMatchersException...... You cannot use argument matchers outside of verification or stubbing..... (The error appears twice in the Failure Trace - but both point to the same line)

In other places in my code the usage of when is done and it's working properly. Also, when debugging my code I found that any(Date.class) returns null.

I have tried the following solutions which I saw other people found useful, but for me it doesn't work:

  1. Adding @After public void checkMockito() { Mockito.validateMockitoUsage(); }
    or
    @RunWith(MockitoJUnitRunner.class)
    or
    @RunWith(PowerMockRunner.class)

  2. Change to PowerMockito.when(new Boolean(DateUtils.isEqualByDateTime(any(Date.class), any(Date.class)))).thenReturn(false);

  3. Using anyObject() (it doesn't compile)

  4. Using notNull(Date.class) or (Date)notNull()

  5. Replace when(........).thenReturn(false);

    with
    Boolean falseBool=new Boolean(false);
    and
    when(.......).thenReturn(falseBool);


Solution

  • So in the end,what worked for me was to export the line that does the exception to some other static function. I called it compareDates.

    My implementation:

    In the class that is tested (e.g - MyClass)
    static boolean compareDates(Date date1, Date date2) { return DateUtils.isEqualByDateTime (date1, date2); }

    and in the test class:
    PowerMockito.mockStatic(MyClass.class); PowerMockito.when(MyClass.compareDates(any(Date.class), any(Date.class))).thenReturn(false);

    Unfortunately I can't say I fully understand why this solution works and the previous didn't.
    maybe it has to do with the fact that DateUtils class is not my code, and I can't access it's source, only the generated .class file, but i'm really not sure about it.


    EDIT

    The above solution was just a workaround that did not solve the need to cover the DateUtils isEqualByDateTime call in the code.
    What actually solved the real problem was to import the DateUtils class which has the actual implementation and not the one that just extends it, which was what I imported before.

    After doing this I could use the original line

    PowerMockito.mockStatic(DateUtils.class);      
    
    PowerMockito.when(DateUtils.isEqualByDateTime (any(Date.class),any(Date.class)).thenReturn(false);
    

    without any exception.