我试图了解对象是如何使用自动传输车辆程序在Java上工作的。我有一种方法可以提高汽车speedIncrease的速度,另一种方法可以获得当前对象currentSpeed的速度。在我的测试用例中,我在TransmissionBox对象renault上创建了一个初始速度为25的对象。speedUp方法将速度提高了2,所以新的速度应该是27。似乎在他第一次调用之后,这个对象就失去了所有的修改。怎么可能呢?
测试:设置
@Before
public void setUp(){
private TransmissionBox renault;
renault = new TransmissionBox(25,10,20,30,40,50);
}测试:速度= 27
@Test
public void speedIncrease(){
assertEquals(27,renault.speedUp().currentSpeed());
}测试:速度= 25
@Test
public void speedIncrease(){
renault.speedUp();
assertEquals(25,renault.currentSpeed());
}
**TransmissionBox class**
public class TransmissionBox {
private int speed;
private int gear;
private int threesholdOne;
private int threesholdTwo;
private int threesholdThree;
private int threesholdFour;
private int threesholdFive;
public TransmissionBox(int iniSpeed, int iniThresholdOne, int iniThresholdTwo, int iniThresholdThree, int iniThresholdFour, int iniThresholdFive){
this.speed = iniSpeed;
this.threesholdOne = iniThresholdOne;
this.threesholdTwo = iniThresholdTwo;
this.threesholdThree = iniThresholdThree;
this.threesholdFour = iniThresholdFour;
this.threesholdFive = iniThresholdFive;
if(speed == 0 && speed < threesholdOne){
this.gear = 1;
}
else if(speed > threesholdOne && speed < threesholdTwo){
this.gear = 2;
}
else if(speed > threesholdTwo && speed < threesholdThree){
this.gear = 3;
}
else if(speed > threesholdThree && speed < threesholdFour){
this.gear = 4;
}
else{
this.gear = 5;
}
}
public TransmissionBox speedUp(){
TransmissionBox fasterCar = new TransmissionBox(speed+2, threesholdOne, threesholdTwo, threesholdThree, threesholdFour, threesholdFive);
return fasterCar;
}
public TransmissionBox speedDown(){
TransmissionBox slowerCar = new TransmissionBox(speed-2, threesholdOne, threesholdTwo, threesholdThree, threesholdFour, threesholdFive);
return slowerCar;
}
public int currentSpeed(){
return this.speed;
}
public int currentGear(){
return this.gear;
}
public String toString(){
return "speed: " + this.speed + "\n gear: " + this.gear;
}
}发布于 2019-09-21 21:14:11
在错误的测试中调用speedUp()
发布于 2019-09-21 21:19:20
注意您在这里所做的事情:
renault.speedUp();
assertEquals(25,renault.currentSpeed());当你打电话给speedUp()时会发生什么?这确实是:
TransmissionBox fasterCar = new TransmissionBox(speed+2, threesholdOne, threesholdTwo, threesholdThree, threesholdFour, threesholdFive);
return fasterCar;现有对象不变,并返回一个新对象。基本上,目前的汽车根本没有“加速”。你刚上了一辆更快的新车。
但是你怎么处理那个新返回的对象呢?什么也没有:
renault.speedUp();renault对象不变,新返回的对象将被忽略/丢弃。renault仍在按设计运行25。
如果希望speedUp()影响当前汽车,请修改当前对象,而不是返回新对象:
public void speedUp(){
this.speed += 2;
}请注意,这不再返回一个对象。除非你真的需要它,否则这个流的语义是没有意义的。(并不是所有的东西都需要流畅的界面。)因此,这个测试需要改变:
@Test
public void speedIncrease(){
assertEquals(27,renault.speedUp().currentSpeed());
}像这样的事情:
@Test
public void speedIncrease(){
renault.speedUp();
assertEquals(27,renault.currentSpeed());
}https://stackoverflow.com/questions/58044101
复制相似问题