我有一个单元测试,它允许我迭代一个包含车辆列表的Collection对象。在每次迭代中,我想检查车辆是否是automobile的实例。所以我的代码看起来像这样:
public class VehicleChecker {
protected boolean checkVehicles(Garage garage) {
for (Vehicle vehicle : garage.getVehicles() {
if (vehicle instanceof Automobile) return true;
}
}
}
所以我写了相应的代码:
@Mock private Garage mockGarage;
@Mock private VehicleCollection mockVehicleCollection;
@Mock private VehicleCollectionIterator mockVehicleCollectionIterator;
@Mock private Vehicle mockVehicle;
@Test
public void testCheckVehicles() {
VehicleChecker testObject = new vehicleChecker();
when(mockGarage.getVehicles()).thenReturn(mockVehicleCollection);
when(mockVehicleCollection.iterator()).thenReturn(mockVehicleCollectionIterator);
when(mockVehicleCollectionIterator.hasNext()).thenReturn(true).thenReturn(false);
when(mockVehicleCollectionIterator.next()).thenReturn(mockVehicle);
boolean result = testObject.checkVehicles(mockGarage);
verify(mockGarage).getVehicles();
}
验证语句出现问题。根据它的写作方式,考试应该可以通过。然而,当我逐步执行代码时,代码完全跳过了for循环。为什么呢?迭代Collection和迭代ArrayList的方式有什么不同吗?如果是这样,我如何正确地模拟这种交互?
你确定你已经用MockitoAnnotations.initMocks初始化了mock吗?