单元测试-简单的断言给出了空指针异常错误 [英] Unit Test - Simple assert is giving null pointer exception error

查看:955
本文介绍了单元测试-简单的断言给出了空指针异常错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的课:

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

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

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.

推荐答案

您实际上是在使用委托模式,因此必须重写setTimeZone方法以将请求转发到SimpleDateFormat对象,如下所示:

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:


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

这篇关于单元测试-简单的断言给出了空指针异常错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆