-1

一切似乎都很完美,但测试用例一直失败,给了我所有这些的 Java.lang.nullPointerException。

这是测试用例

@Test
    public void validMonths() {
        DayOfWeek dow = new DayOfWeek(1, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("January") == 0);
        dow = new DayOfWeek(2, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("February") == 0);
        dow = new DayOfWeek(3, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("March") == 0);
        dow = new DayOfWeek(4, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("April") == 0);
        dow = new DayOfWeek(5, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("May") == 0);
        dow = new DayOfWeek(6, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("June") == 0);
        dow = new DayOfWeek(7, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("July") == 0);
        dow = new DayOfWeek(8, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("August") == 0);
        dow = new DayOfWeek(9, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("September") == 0);
        dow = new DayOfWeek(10, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("October") == 0);
        dow = new DayOfWeek(11, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("November") == 0);
        dow = new DayOfWeek(12, 1, 1900);
        assertTrue(dow.getMonthString().compareTo("December") == 0);
    }

这是我的方法

public String getMonthString(){
         String[] arrayOfMonths = new String[11];
         arrayOfMonths[0] = "January";
         arrayOfMonths[1] = "February";
         arrayOfMonths[2] = "March";
         arrayOfMonths[3] = "April";
         arrayOfMonths[4] = "May";
         arrayOfMonths[5] = "June";
         arrayOfMonths[6] = "July";
         arrayOfMonths[7] = "August";
         arrayOfMonths[8] = "September";
         arrayOfMonths[9] = "October";
         arrayOfMonths[10] = "November";
         arrayOfMonths[11] = "December";
         if (this.myMonth > 0 && this.myMonth <=12){
             return arrayOfMonths[this.myMonth-1];
         }
         else{
             return "NO_VALUE";
         }
     }

有谁知道发生了什么?

4

1 回答 1

1

arrayOfMonths 的大小必须为 12,而不是 11。

编辑:谁赞成我不应该有。:-) 那会抛出 ArrayIndexOutOfBoundsException,而不是 NPE。这仍然是一个真正的问题,只是不是他遇到的问题。

于 2013-09-16T18:11:01.760 回答