Reputation:
Below is my method which gives me the date of either recent Monday
or recent Thursday
in the format of YYYYMMDD
.
Today is Saturday, so it should return date for Thursday in the format of YYYYMMDD
so it will be - 2014027
public static String getDate() {
Calendar cal = Calendar.getInstance();
try {
int dow = cal.get(Calendar.DAY_OF_WEEK);
switch (dow) {
case Calendar.THURSDAY:
case Calendar.FRIDAY:
case Calendar.SATURDAY:
case Calendar.SUNDAY:
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY) {
cal.add(Calendar.DATE, -1);
}
break;
case Calendar.MONDAY:
case Calendar.TUESDAY:
case Calendar.WEDNESDAY:
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
cal.add(Calendar.DATE, -1);
}
break;
}
} catch (Exception ex) {
// log error
}
return toDateFormat.format(cal.getTime());
}
So my question is, how do I mock the Calendar getInstance
method so that I can easily junit getDate
method? I have never mocked it before so I am facing some problem?
Can anyone provide a simple example if possible on my example?
Upvotes: 1
Views: 234
Reputation: 96385
If this was my code I would extract the Calendar variable into another method, overloading the method so that there is one version that takes the Calendar as a parameter and one version with no arguments, like this:
public static String getDate() {
return getDate(Calendar.getInstance());
}
public static String getDate(Calendar cal} {
// your example code
}
This way you can write tests exercising your logic in getDate without having to use any mocks. If you really want to cover the no-args version of the method then you can use PowerMock to mock Calendar's getInstance method (here's a question with examples of that).
Upvotes: 2