1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java – 在JUnit测试用例中访问列表

java – 在JUnit测试用例中访问列表

时间:2021-11-30 08:35:27

相关推荐

java – 在JUnit测试用例中访问列表

我有这个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>();@Beforepublic 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;}@Testpublic void shouldGetLicensesWithAParticularColour() throws Exception { assertEquals(, parkingLot.licenseWithAParticularColour("White"));}

}

在上面的测试用例中,我想检查List是否填充了正确的许可证.

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")); }}

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

@Testpublic void shouldNotGetLicensesWithANullColour() throws Exception { ... assertEquals(expected, parkingLot.licenseWithAParticularColour(null));}@Testpublic void shouldNotGetLicensesWithAnUnknownColour() throws Exception { ... assertEquals(expected, parkingLot.licenseWithAParticularColour("unknown"));}

一些补充说明:

>我不会使用Car []作为插槽,而是使用List< Car>.

>你真的不需要List< String> ParkingLot中的列表(以及licenseWithAParticularColour的当前实现是错误的).

>我会用Enum作为颜色.

来源:/content-1-237301.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。