This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


4年前关闭。




我有这种方法可以测试

public static AccountingYear newInstance(Date startingDate, Date endingDate) {
    if ((startingDate == null) || (endingDate == null)) {
        throw new AccountingRuntimeException(
                "the range specify is not correct");
    }

    AccountingDaoFactory daoFactory = (AccountingDaoFactory) UnitOfWork
            .getCurrent().getDaoFactory();
    AccountingYear lastAccoutingYear = daoFactory.getAccountingYearDao()
            .getLastAccountingYear();
    Date startDate = lastAccoutingYear.startingDate;
    Date endDate = lastAccoutingYear.endingDate;
    if (lastAccoutingYear != null
            && isDateRangesOverlap(startDate, endDate, startingDate,
                    endingDate)) {
        throw new AccountingYearCollisionException();
    }
    if (endingDate.before(startingDate)) {
        throw new EndingDateIsBeforeStartingDateException();
    }
    AccountingYear newAccountingYear = new AccountingYear(startingDate,
            endingDate, true);
    if (isOldAccountingYear(startDate, endingDate)) {
        newAccountingYear.setSatus(AccountingYearState.OLD_AND_NOT_CLOSED);
    }
    newAccountingYear.save();
    return newAccountingYear;
}


这是对应的测试

@Test
public void newAccountingYearTest() throws Exception {
    AccountingYear accountingYear = Mockito.mock(AccountingYear.class);
    Mockito.when(accountingYear.getAllPeriods()).thenCallRealMethod();
    objectToTest = AccountingYear.newInstance(startingDate, endingDate);
    Assert.assertNotNull(objectToTest);
    Assert.assertEquals(2, objectToTest.getAllPeriods().size());
    Assert.assertEquals(AccountingPeriodType.Opening, objectToTest
            .getAllPeriods().get(0).getType());
    Assert.assertEquals(AccountingPeriodType.Closing, objectToTest
            .getAllPeriods().get(1).getType());
}


当我运行测试时,我遇到以下异常:Java.lang.nullPointerexception,位于Java.util.Date.getMillisOf,Date.before()。
这是给出异常的isOldAccountingYear代码

public static boolean isOldAccountingYear(Date startDate, Date endingDate2) {
    if (endingDate2.before(startDate)) {
        return true;
    } else {
        return false;
    }
}


请你能帮我解决问题

最佳答案

您对症状的描述尚不清楚,但似乎您是在说before中的isOldAccountingYear调用中引发了NPE。这意味着startDate参数是null。 (如果endingDate2null,则NPE将由isOldAccountingYear本身抛出,而不是由before方法抛出。)

我认为您在调用isOldAccountingYear的代码中有一个错误:

if (isOldAccountingYear(startDate, endingDate)) {


先前的代码已经仔细检查了endingDate参数,不能将其设为null。但是startDate是一个局部变量,其值来自lastAccoutingYear字段。可能是null。我怀疑那是……导致了NPE。

我不了解此代码的真正意图(您的变量命名无济于事!),但我怀疑以上代码应该是:

if (isOldAccountingYear(startingDate, endingDate)) {

10-04 19:20