package b;
public class MyDate {
private int year;
private int month;
private LeapJduge lj;
public MyDate(int year, int month, LeapJduge lj) {
super();
this.year = year;
this.month = month;
this.lj = lj;
}
int lastDayMonth() {
int i = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
i = 31;
break;
case 4:
case 6:
case 9:
case 11:
i = 30;
break;
case 2:
i = lj.isLeap(year) ? 29 : 28;
default:
throw new IllegalArgumentException("month is out of range");
}
return i;
}
}
package b;
public interface LeapJduge {
boolean isLeap(int year);
}
package b;
import org.junit.Assert;
import org.junit.Test;
public class 测试 {
@Test
public void Tset1() {
MyDate a=new MyDate(2000, 1, null);
Assert.assertEquals(31, a.lastDayMonth());
}
@Test
public void Tset2() {
MyDate a=new MyDate(1999, 2, null);
Assert.assertEquals(28, a.lastDayMonth());
}
@Test
public void Tset3() {
MyDate a=new MyDate(2000, 2, null);
Assert.assertEquals(28, a.lastDayMonth());
}
Test2 和Test3 都抛出了了空指针异常,但是Test1没有
求大佬指教!!
出现在2月份没有实例化对象LeapJduge,new MyDate(1999, 2, null);不能直接传null,要改成如new MyDate(1999, 2, new LeapJduge());
因为第一个用例月份是1,不会执行对象的方法,所以不存在空指针异常。
后两个2月会执行 lj.isLeap 方法,涉及到对象操作了,所以抛异常了。
加固代码:执行 . 操作之前,判断是否为空。