java - 使用依赖于其他类的类进行 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 类中错误地创建项目的地方。
解决方案
在你的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());
}
推荐阅读
- android - SMS Retriever API 的谷歌和华为哈希码计算方式相同吗?
- apache-kafka - 在独立模式下无法连接和描述 Kafka 集群
- html - 如何删除网格中的多余空格?
- sql - 如何在 SQL 的新列中显示每年的结果
- javascript - 使用jquery只显示img src而不显示音频和视频src
- laravel - 如何将文件从本地存储上传到 S3?
- javascript - 两个path2D之间的javascript画布交集
- spring - Spring Boot JPA Like 查询
- java - 从列表参数中选择值
- oracle - 如何将 Oracle 数据库连接到 Oracle Developer?