过去几天我一直试图找到一个状态模式工作的例子。该任务已被设置为主要课程模块的一部分。我确实在这里找到了一个使用相同示例的线程,但是在我看来并没有正确地做到这一点,因为程序应该适用于我想要做的任何类型的测试标准。请点击此处:state design pattern。我把它缩小到了,我相信正常状态类中的if语句,所以我已经删除了状态和弹药的set / getters,但是如果需要它我可以在以后添加它
目前它正在完成第一个assertEquals完全正常,但是一个它进入第二个它会抛出一个nullpointexception。所以我的问题是,我做错了什么,或错过了什么,使用if语句返回if语句的第二部分的nullpointexception?我得到的严厉回答并没有帮助,因为我想要的只是一双新鲜的眼睛,看看我做了什么来找到错误,而不是完成我的整个任务,因为我只需要一些帮助解决这个小问题。此外,我已经知道NPE是什么,在这种情况下它发生了,因为声明的第二部分没有按照指定的标准进行初始化。
提前谢谢
public class Railgun {
static int MAX_AMMO = 10;
public String fire(Point p, int round){
System.out.println(p + " " + round);
// System.out.println("ASA W " + state.fire(p, round));
return state.fire(p, round);
}
}
处于正常状态的火法:
public String fire(Point p, int round) {
// NormalState normal = new NormalState();
NeedAmmoState needAmmo = new NeedAmmoState();
System.out.println("akhdka " + round);
ammo-= round;
int round1 = round;
int result1 = 0 + round1;
if(ammo >= 0 && result1 == round1)
{
System.out.println(result1);
return "Fire order: Success "+ result1 + "/" + round1;
}
else if((ammo < 0) && (ammo != -result1))
{
railgun.ammo = 0;
return "Fire order: Partial success " + result1 + "/" + round1;
}else
{ System.out.println("Fail: " + ammo);
railgun.setState(needAmmo);
return "Fire order: Failure "+ result1 + "/" + round1;
}
}
Junit测试:
public void testFire() {
final Railgun railgun = new Railgun();
final int numRounds = 6;
final int x = 100;
final int y = 340;
// This fire mission should be completely successful
String actualResult = railgun.fire(new Point(x, y), numRounds);
String expectedResult = "Fire order: Success 6/6";
System.out.println("ASAS " + actualResult);
assertEquals(expectedResult, actualResult);
// This fire mission should be partially successful
actualResult = railgun.fire(new Point(x, y), numRounds);
//System.out.println(actualResult);
expectedResult = "Fire order: Partial success 4/6";
assertEquals(expectedResult, actualResult);
// This fire mission should fail
actualResult = railgun.fire(new Point(x, y), numRounds); expectedResult = "Fire order: Failure 0/6";
assertEquals(expectedResult, actualResult);
// Check state change to NeedAmmo state
assertEquals(railgun.getState().getClass(), NeedAmmoState.class);
}