简体   繁体   English

创建Double以测试null检查时引发的null指针异常

[英]Null pointer exception thrown when creating a Double to test null check

This may be a stupid question, but I have a method that will convert Doubles or BigDecimals to a formatted String: 这可能是一个愚蠢的问题,但是我有一个方法可以将Doubles或BigDecimals转换为格式化的String:

//There is also a method that accepts BigDecimals
public String convertToCurrencyString(Double aAmount) {
    if(aAmount == null){
        return "$0.00";
    }
    NumberFormat numFormat = DecimalFormat.getCurrencyInstance(Locale.US);
    numFormat.setMinimumFractionDigits(2);
    String amount = numFormat.format(aAmount);
    return amount;
}

I'm currently trying to test this method with JUnit by instantiating a Double: 我目前正在尝试通过实例化Double来使用JUnit测试此方法:

Double nullDouble = new Double(null);

The problem is a NullPointerException is being thrown when the creating the Double. 问题是创建Double时抛出NullPointerException。 Is there a way to stop this happening, or is this normal behaviour? 有没有办法阻止这种情况的发生,或者这是正常的行为? The need for the null check is that there are some older records in a database that have these Doubles and BigDecimals set to null 需要执行null检查的是数据库中有一些较旧的记录,这些记录将Doubles和BigDecimals设置为null

new Double(null) calls the Double(String) constructor, which tries to parse the given string into a double. new Double(null)调用Double(String)构造函数,该构造函数尝试将给定的字符串解析为double。 But with a null String it fails with a NullPointerException. 但是如果使用null字符串,它将失败,并显示NullPointerException。

The proper way to pass a null Double to your method is to simply call: 将null Double传递给您的方法的正确方法是简单地调用:

String resultForNull = convertToCurrencyString(null);

Also since your method does not use the enclosing class' state, it may make sense to make it static . 同样,由于您的方法不使用封闭类的状态,因此将其设置为static可能是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM