首页 > 解决方案 > array.length 在junit中抛出 NullPointerException 但不是在应用程序运行时

问题描述

我遇到了一个奇怪的问题。我对编码仍然很陌生,所以这可能源于我对数组性质的误解。我的问题是:我正在尝试为我的应用程序中的一些数组编写单元测试,我在其中调用 arr.length ,然后抛出 NPE。数组在类的构造函数中初始化,所以这不是问题。我尝试用每个索引处的值初始化它们,看看是否改变了任何东西,但它没有。最让我困惑的是,当我在运行应用程序时在同一个数组上调用 arr.length 时,我得到了一个值。

我缺少关于 JUnit 的东西吗?

正在测试的方法不完整。当我开始遇到 NPE 时,我正在编写它,所以我从未真正接触过将值分配给数组的代码。这是测试和正在测试的类:

@Test
void testCFArray() throws IOException {
    WebReaderFilter adder = new WebReaderFilter();
    Stock stock = new Stock("INTC");
    stock.setProfile(adder.getStockDetails(stock.getTicker()));

// 这个方法调用会抛出 NPE

    stock.setArrays(stock.getProfile());
    BigInteger[] arr = stock.getCashFlowArray();
    assertEquals(BigInteger.valueOf(33145000000L), arr[0]);
}

package companyValueModel;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;

public class Stock {

    private String ticker;
    private BigDecimal currentPrice;

    private BigInteger[] freeCashFlow;
    private BigInteger[] cashFlow;
    private BigInteger[] debt;
    private BigDecimal[] divPerShare;

/*
 * Keys: [companyName], [EBITDA], [Enterprise Value], [description], [industry],
 * [yearHigh], [price], [Total shareholders equity], [Goodwill and Intangible
 * Assets], [Capital Expenditure], [sector], [yearLow], [marketCap], [Dividend
 * payments], [ticker], [Revenue Growth], [Cash and short-term investments],
 * [Net Income], [Revenue]
 * 
 * Array keys: [Long-term debt-1], [Free Cash Flow0], [Long-term debt-2],
 * [Long-term debt0], [Free Cash Flow-2], [Dividend per Share0], [Free Cash
 * Flow-1], [Dividend per Share-1], [Operating Cash Flow0], [Operating Cash
 * Flow-1], [Operating Cash Flow-2]
 * 
 * keys with numbers at the end represent (0) = this year, (-1) = year prior,
 * etc.
 */

    private HashMap<String, String> profile;

    public Stock(String ticker) {
        this.ticker = ticker;
    }

    public Stock(HashMap<String, String> profile) {
        this.profile = profile;
        this.ticker = profile.get("ticker");
        freeCashFlow = new BigInteger[3];
        cashFlow = new BigInteger[3];
        debt = new BigInteger[3];
        divPerShare = new BigDecimal[2];
    }

    public HashMap<String, String> getProfile() {
        return profile;
    }

    public void setProfile(HashMap<String, String> profile) {
        this.profile = profile;
    }

    public String getTicker() {
        return ticker;
    }

    public void setCurrentPrice(BigDecimal price) {
        currentPrice = price;
    }

    public BigDecimal getCurrentPrice() {
        return currentPrice;
    }

    public void setArrays(HashMap<String, String> profile) throws NumberFormatException {
        int j = 0;
//      this line throws the NPE.  It disappears if I replace cashFlow.length with 3

        for (int i = 0; i < cashFlow.length; i++) {

//          This line was to verify that the key existed (it does)

            System.out.println(profile.get("Operating Cash Flow" + j));

//          also as an aside if anybody could tell me whether I'm parsing this string properly to bigInt I would appreciate it.

            double flow = Double.parseDouble(profile.get("Operating Cash Flow" + j));
            BigInteger cf = BigInteger.valueOf((long) flow);
            j--;

// Here is where the assigning code would have gone

        }
    }

    public BigInteger[] getCashFlowArray() {
        return cashFlow;
    }

    public BigInteger[] getFreeCashFlowArray() {
        return freeCashFlow;
    }

    public BigInteger[] getDebtArray() {
        return debt;
    }

    public BigDecimal[] getDivPerShare() {
        return divPerShare;
    }
}

我突然想到,我可以为单元测试编写一个带有常量的类似方法,并为程序使用另一个方法,但这会使该方法没有适当的单元测试,这不会引起我的兴趣。最后,数组可能不是必需的,但我认为它们以后会很方便。我要求进一步了解,以便如果我再次遇到这个问题,我知道需要做什么。

标签: javaarraysjunitnullpointerexception

解决方案


您在测试用例中创建Stock对象时使用字符串参数构造函数。

--> 在那初始化 cashFlow..

public Stock(String ticker) {
    this.ticker = ticker;
    cashFlow = new BigInteger[3]; // add this
}

或者

-->在测试用例中初始化Stock对象时使用另一个 HashMap 参数构造函数。


推荐阅读