This question already has an answer here:
I am writing a unit test to verify that both the ISO8601Utils (deprecated class which I replaced with SimpleDateFormat) and SimpleDateFormat has the same format.
My class:
public static class ISO8601DateFormat extends DateFormat {
public static final long serialVersionUID = 3549786448500970210L;
public ISO8601DateFormat() {}
@Override
public StringBuffer format(Date date, StringBuffer
toAppendTo, FieldPosition fieldPosition) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-
dd'T'HH:mm:ss.SSS'Z'");
String value = dateFormat.format(date);
//This used to be ISO8610Utils.format(date, true) which
//is now deprecated and I replaced it with the new one. I
//want to verify this part so that the newly replaced
//dateFormat still returns the same formatted output as the
//ISO8610Utils
toAppendTo.append(value);
return toAppendTo;
}
public Date parse(String source, ParsePosition pos) {
pos.setIndex(source.length());
return ISODateTimeFormat.dateTimeParser().parseDateTime(source).toDate();
}
public Object clone() {
return this;
}
public String toString() {
return this.getClass().getName();
}
}
My test method:
@Test
public void testDateFormat() {
df = new DefaultHttpClientUtil.ISO8601DateFormat();
Date date = new Date();
//df.setTimeZone(TimeZone.getTimeZone("GMT")); I'm getting NPE
for this line
assertThat(df.format(date)).isEqualTo(ISO8601Utils.format(date,
true));
}
However, I am getting null pointer exception for the commented line. I assume it has to do with injecting or mocking object, but I am not sure how I should approach this problem.
You're actually applying delegation pattern, so that it's essential to override
setTimeZone
method to forward request to the SimpleDateFormat object, just as follows: