【发布时间】:2018-05-02 13:16:02
【问题描述】:
你好我有这个类项目
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 类中错误地创建项目的地方。
【问题讨论】:
-
@Test 中的
stock是一个新实例,因此它不包含任何内容。 -
Stock类中没有添加任何项目的方法,因此您永远无法向其中添加任何项目(因此您的测试按预期返回 0。)另外,为什么 @987654326 @扩展HashMap? (您的 setup() 方法确实创建了一个项目,但它不会添加到任何内容中。)