3

I am trying to mock a SimpleDateFormat object but Mockito says I have the wrong number of args. Code:

 SimpleDateFormat spyDateFormat = spy(new SimpleDateFormat(DateFormatManager.MAIN_ACTIVITY_TITLE_FORMAT));
 // exception points to below line
 when(spyDateFormat.format(any(Date.class))).thenReturn("foo format");

exception:

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

The method exists in DateFormat, its parent:

http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)

Fiddled around with switching to DateFormat, using spy. No luck.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
browep
  • 5,057
  • 5
  • 29
  • 37

2 Answers2

5

The format(Date) method is final, so Mockito cannot spy it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I just want to add: You may want to have a look at PowerMock if you need to mock final methods: http://stackoverflow.com/questions/3793791/final-method-mocking – Robert Reiner Oct 08 '15 at 16:59
2

From the Mockito FAQ:

What are the limitations of Mockito

Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.

Shagayag
  • 81
  • 13