Reputation: 4375
So here's my test :
@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..
}
Here's my service implementation:
@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;
}
I explained problem in the comments. check my test.
Upvotes: 0
Views: 77
Reputation: 4973
I ran your Test method with your implementation and your only assert was successful:
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class InventoryServiceTest {
@Mock
private ItemRepository itemRepository;
@InjectMocks
private InventoryService inventoryService;
@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..
}
}
Because yes they both have a size of one:
Upvotes: 0
Reputation: 160271
demoItems
list changes because you're using it as your list of items: you return demoItems
from the service's findAll()
method.
You then remove items with quantity zero. They're the same list. Not weird at all.
Upvotes: 2