我有这个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上的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作为颜色。
  • 10-06 09:16