0

所以这是我的测试:

@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;
}

我在评论中解释了问题。检查我的测试。

4

2 回答 2

2

demoItemslist 更改是因为您将其用作项目列表:您demoItems从服务的findAll()方法返回。

然后删除数量为零的项目。它们是同一个列表。一点都不奇怪。

于 2013-11-09T15:44:30.537 回答
0

我用你的实现运行了你的测试方法,你唯一的断言是成功的:

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..
    }

}

因为是的,它们的大小都是一个: 在此处输入图像描述

于 2013-11-09T17:04:52.273 回答