Search code examples
javaunit-testingmockingmockitojunit3

Mock Date object using Mockito


A method of MyService class returns java.util.Date object and MyManager class is calling that method of MyService class. I am writing the test case for MyManager class.
when I mock

Mockito.when(manager.getDate())).thenReturn((Date)Mockito.any())

is not working. Could some one help me on this please?


Solution

  • I don't think you are using the syntax correctly. The any idiom is used for matching arguments when a method is called, not for specifying the return value of a mocked called. See Matchers for details on how these work.

    Try providing a real date as your return value.

    I gather from your line of code that you might be using Mockito incorrectly. If you are testing Manager using a mocked Service then your code should likely look something like:

    Date testDate = new Date("01/01/1970");
    Service mockedService = mock(Service.class);
    when(service.getDate()).thenReturn(testDate);
    testManager.setService(service);
    assertEquals(testDate, testManager.getServicesDate());
    

    In other words, you wouldn't normally be mocking a Manager object (as implied by your code) if you are testing the Manager class.