所以这是我的测试:
@Test
public void returnsAllItemsInStock() {
List<Item> demoItems = new ArrayList<Item>();
Item demoItemOne = new Item();
demoItemOne.setQuantity(0);
Item demoItemTwo = new Item();
demoItemTwo.setQuantity(17);
demoItems.add(demoItemOne);
demoItems.add(demoItemTwo); // List size currently 2
Mockito.when(itemRepository.findAll()).thenReturn(demoItems);
List<Item> items = inventoryService.allItemsInStock();// Here demoItems size somehow changes to 1
Assert.assertEquals("List's size expected not to match", items.size(), demoItems.size()); // This one should fail because sizes shouldn't be equal, but they are..
}
这是我的服务实现:
@Override
@Transactional
public List<Item> allItemsInStock() {
List<Item> items = new ArrayList<Item>();
items = (List<Item>) itemRepository.findAll();
for (Iterator<Item> it = items.iterator(); it.hasNext();) {
Item item = it.next();
if (item.getQuantity() <= 0) {
it.remove();
}
}
return items;
}
我在评论中解释了问题。检查我的测试。