单元测试 - 简单断言给出空指针异常错误

Unit Test - Simple assert is giving null pointer exception error

我正在编写一个单元测试来验证 ISO8601Utils(已弃用 class,我用 SimpleDateFormat 替换)和 SimpleDateFormat 是否具有相同的格式。

我的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();
    }
}

我的测试方法:

  @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));
  }

但是,我收到注释行的空指针异常。我认为它与注入或模拟对象有关,但我不确定我应该如何解决这个问题。

您实际上是在应用 delegation pattern,因此必须覆盖 setTimeZone 方法以将请求转发到 SimpleDateFormat 对象,如下所示:


public static class ISO8601DateFormat extends DateFormat {
    ...

    // MUST make dateFormat reusable.
    private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    @Override
    public void setTimeZone(TimeZone zone)
    {
        dateFormat.setTimeZone(zone);
    }
}