为什么这个JUnit测试用例失败了?

时间:2013-09-16 18:09:50

标签: java testing junit

一切看起来都很完美但测试用例仍然失败,给了我所有这些的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";
         }
     }

有谁知道发生了什么事?

1 个答案:

答案 0 :(得分:1)

arrayOfMonths需要大小为12而不是11。

编辑:任何支持我的人都不应该。 :-)那将抛出和ArrayIndexOutOfBoundsException,而不是NPE。这仍然是一个真正的问题,而不是他所拥有的那个问题。