我有这个ParkingLot.java
public class ParkingLot {
private final int size;
private Car[] slots = null;
List<String> list = new ArrayList<String>();
public ParkingLot(int size) {
this.size = size;
this.slots = new Car[size];
}
public List licenseWithAParticularColour(String colour) {
for (int i = 0; i < slots.length; i++) {
if (slots[i].getColour() == colour) {
System.out.println(slots[i].getLicense());
list.add(slots[i].getLicense());
return list;
}
}
return null;
}
}
我创建了一个ParkingLotTest.java,如下所示
public class ParkingLotTest {
private Car car1;
private Car car2;
private Car car3;
private Ticket ticket1;
private Ticket ticket2;
private Ticket ticket3;
private ParkingLot parkingLot;
private List<String> list = new ArrayList<String>();
@Before
public void intializeTestEnvironment() throws Exception {
this.car1 = new Car("1234", "White");
this.car2 = new Car("4567", "Black");
this.car3 = new Car("0000", "Red");
this.parkingLot = new ParkingLot(2);
this.ticket1 = parkingLot.park(car1);
this.ticket2 = parkingLot.park(car2);
this.ticket3 = parkingLot.park(car3);
this.list = parkingLot.list;
}
@Test
public void shouldGetLicensesWithAParticularColour() throws Exception {
assertEquals(, parkingLot.licenseWithAParticularColour("White"));
}
}
在上面的测试用例中,我想检查列表是否填写了正确的许可证。 1.如何在ParkingLotTest.java中创建一个字段,以便第一个类中的List与第二个类文件中的列表相同。
答案 0 :(得分:5)
首先,我认为你list
上不需要ParkingLot
,所以你的问题实际上没有多大意义:)
其次,只需在每个测试方法中设置预期结果:
public class ParkingLotTest {
//...
@Test
public void shouldGetLicensesWithAParticularColour() throws Exception {
List<Car> expected = new ArrayList<Car>();
expected.add(...);
assertEquals(expected, parkingLot.licenseWithAParticularColour("White"));
}
}
不要忘记测试意外值或特殊情况。例如:
@Test
public void shouldNotGetLicensesWithANullColour() throws Exception {
...
assertEquals(expected, parkingLot.licenseWithAParticularColour(null));
}
@Test
public void shouldNotGetLicensesWithAnUnknownColour() throws Exception {
...
assertEquals(expected, parkingLot.licenseWithAParticularColour("unknown"));
}
其他一些评论:
Car[]
用于slots
,而是使用List<Car>
。List<String> list
中的ParkingLot
(licenseWithAParticularColour
的当前实现是错误的。)Enum
作为颜色。答案 1 :(得分:2)
但是你想要吗?
这有些开玩笑,但是你通常构建一个List
会很好 - 只要它与你想要的测试界面列表一致。
对于这种特殊情况,我建议您构建一个List<Car>
作为测试参考,然后访问每个Car
并停放它。然后,您可以从该参考列表构建许可证列表,并将其与停车场之一进行比较。只需确保您的迭代方向正确。
答案 2 :(得分:1)
Pascal的答案对我有用。
@Pascal再次,我做了这个功能:
public List getSlotNumbersWithAParticularColour(String colour) {
List<Integer> listOfTicketsWithAColour = new ArrayList<Integer>();
for (int i = 0; i < slots.length;) {
if (slots[i].getColour() == colour) {
listOfTicketsWithAColour.add(i);
}
return listOfTicketsWithAColour;
}
return null;
}
错误不在for循环中,添加i ++是Eclipse的“死代码”。添加i ++不会造成任何差异。
以及相应的测试用例:
public void getSlotNumbersWithAGivenColour() throws Exception {
List<String> expected = new ArrayList<String>();
expected.add("0");
expected.add("3");
assertEquals(expected, parkingLot.getSlotNumbersWithAParticularColour("White"));
}
测试失败。该函数仅返回0,而不是0,3。知道为什么吗?