访问JUnit测试用例中的列表

the*_*cer 4 java

我有这个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;
}
Run Code Online (Sandbox Code Playgroud)

}

我创建了一个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"));

}
Run Code Online (Sandbox Code Playgroud)

}

在上面的测试用例中,我想检查List是否填充了正确的许可证.1.如何在ParkingLotTest.java中创建一个字段,以便第一个类中的List与第二个类文件中的列表相同.

Pas*_*ent 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"));
    }

}
Run Code Online (Sandbox Code Playgroud)

并且不要忘记测试意外值或特殊情况.例如:

@Test
public void shouldNotGetLicensesWithANullColour() throws Exception {
    ...
    assertEquals(expected, parkingLot.licenseWithAParticularColour(null));
}

@Test
public void shouldNotGetLicensesWithAnUnknownColour() throws Exception {
    ...
    assertEquals(expected, parkingLot.licenseWithAParticularColour("unknown"));
}
Run Code Online (Sandbox Code Playgroud)

一些补充说明:

  • 我不会用Car[]slots,但一个List<Car>.
  • 你真的不需要List<String> listin ParkingLot(以及当前实现的licenseWithAParticularColourbug).
  • 我会用一种Enum颜色.

  • 测试关闭案例为+1.对于`null`的情况,我会说抛出一个'NullPointerException`是返回空列表的合理替代方法,所以利用`@Test(expected = ...)`是另一种方法. (2认同)