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

时间:2019-02-20 02:10:21

标签: java unit-testing junit nullpointerexception date-format

我正在编写一个单元测试,以验证ISO8601Utils(已被SimpleDateFormat取代的不赞成使用的类)和SimpleDateFormat是否具有相同的格式。

我的课:

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

但是,我在注释行中得到了空指针异常。我认为这与注入或嘲笑对象有关,但是我不确定应该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

您实际上是在应用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);
    }
}