首页 > 解决方案 > 使用依赖于其他类的类进行 JUnit 测试

问题描述

嗨我有这个类项目

public class Item implements Cloneable {

    private String name;
    private int reorderAmount;


    public Item(String name, int reorderAmount) {
        this.name = name;
        this.reorderAmount = reorderAmount;

     }


   /**
     * @return The Amount of a reorder.
     */
    public int getReorderAmount() {
        return reorderAmount;
    }
}

我的另一门课是股票

public class Stock extends HashMap {

    private HashMap<String, Item> stock;

    /**
     * Constructor. Creates a stock. 
     */
    public Stock() {
        stock = new HashMap<>();
    }

    /**
     * Calculates the total Quantity of Items for the next Order.
     * @return Number of total reorder quantity.
     */
    public int getTotalReorderAmount() {
        int reorderQuantity = 0;
        for (Item item : (Collection<Item>) this.values()) {
            reorderQuantity += item.getReorderAmount();
        }
        return reorderQuantity;
    }
}

我在运行 JUnit 测试时遇到了麻烦,因为我缺乏对一个类如何影响另一个类的理解。

public class StockTests  {

            Stock stock; 
            Item item; 


            // Clear the item and stock object before every test 
            @Before
            public void setUp() {
                String name = "bread";
                Integer reorderAmount = 100; 
                item = new Item(name, reorderAmount);

                stock = null;
            }

            /*
             * Test 1: Test the total number of items needed.
             */
            @Test
            public void testReorderAmount() {
                stock = new Stock();
                assertEquals(100, stock.getTotalReorderAmount());
            }

}

我目前所做的是在我的 Junit 测试类的@before 中创建了一个项目“面包”,其中 100 作为再订购量。我正在测试我的 Stock 类中的 getTotalReorderAmount 方法是否返回 100,但是我的 JUnit 结果告诉我它返回 0。这是我认为我在 JUnit 类中错误地创建项目的地方。

标签: javaclassjunit

解决方案


在你的testReorderAmount方法中,你必须设置item你创建的。

首先修改你的Stock类,使其具有在private HashMap<String, Item> stock. 即你的课Stock可能看起来像:

public class Stock {

  .............

    private HashMap<String, Item> stock;

    public void addItemToStock(String itemName, Item item){
       stock.put(itemName, item);
    }

    /**
     * Constructor. Creates a stock. 
     */
    public Stock() {
        stock = new HashMap<>();
    }
 .........

}

其次,在您的 junit 测试中设置地图item内部。stock

您的测试方法将如下所示:

 /*
 * Test 1: Test the total number of items needed.
 */
@Test
public void testReorderAmount() {
    stock = new Stock();
    stock.addItem("bread", this.item);
    assertEquals(100, stock.getTotalReorderAmount());
}

推荐阅读