Issue
i am using mockito and i have a custom date class and i want to be able to mock this date class in my test class, so i tried the following:
MVDate date = Mockito.mock(MYDate.class);
Mockito.when(date.get(Calendar.MONTH)).thenReturn(5);
MYDate Class:
public class MYDate extends GregorianCalendar implements Comparable<Calendar> {
public MYDate() {
setTime(new Date());
}
}
but when trying to print the new MYDate();
it always prints the current date.
please advise how should i mock the calendar class so that i can test on specific date for all methods who create new data instance.
Solution
Please note: I wrote this answer in 2013. Things are a bit different now. Basil Bourque's answer is the correct one.
I would use a Factory class to make the Date
objects, rather than using new Date()
. Have a second constructor for MyDate
where you can pass the Factory. Then use a mock of the Factory, which you can set up to return whatever date you like.
public class DateFactory{
public Date makeDate(){
return new Date();
}
}
-----------------------------------
public class MyDate extends GregorianCalendar implements Comparable<Calendar>{
public MyDate(){
this(new DateFactory());
}
MyDate(DateFactory factory){
setTime(factory.makeDate());
}
}
Answered By - Dawood ibn Kareem