java - 这是 Hash Map 的有效单元测试吗?
问题描述
如果我以写方式编写单元测试,我试图理解。我有一个哈希图,用于存储我的客户注册。我正在尝试为我的 createCustomer 方法编写单元测试。如果我的方向正确,有人可以给我指点吗?
void addCustomer () {
System.out.println ();
String customerName = getString ("Enter Customer Name with cappital letar: ");
String customerAddress = getString ("Enter Customer Address with cappital letar: ");
int customerPhone = getInt ("Enter Customer phone:");
int customerID = checkID ();
Customer customer = new Customer (customerName, customerAddress, customerID, customerPhone);
customerList.put (customerID, customer);
System.out.println ("Customer Added");
}
@Test
public void addCustomerTest () {
HashMap<Integer,Customer> customerList = new HashMap<> ();
String customerName = "Anna";
String customerAddress = "London";
int customerPhone = 1010101;
int customerID = 1000;
Customer customer = new Customer (customerName, customerAddress, customerID, customerPhone);
customerList.put (customerID, customer);
assertTrue(customerList.containsKey(customerID) && customerList.get(customerID) != null);
}
解决方案
HashMap
当前您对此类进行单元测试时,您不是作者。
所以不,你没有以正确的方式测试你的代码。
您想要的单元测试是您的类的 API:即addCustomer()
.
这Map
是一个实现细节,可能会随着时间而改变,您不想测试。
您的单元测试应如下所示:
@Test
public void addCustomer() {
CustomerRepository repo = new CustomerRepository();
String customerName = "Anna";
String customerAddress = "London";
int customerPhone = 1010101;
int customerID = 1000;
// Mock the System IN to read these values
// ...
// invoke the method under test
repo.addCustomer();
// assert that the repo contains the new object
Customer actual = repo.findCustomerById(customerID);
assertNotNull(actual);
assertEquals(customerName, actual.getCustomerName());
assertEquals(customerID, actual.getCustomerID());
// and so for for each field
}
推荐阅读
- python - 尽管已安装它们,但在我的 Anaconda Jupyter Notebook 中导入 eval_utils、pattern3 时出错
- networking - 如何在不使用云服务的情况下通过 gRPC 连接位于两个不同物理位置的 2 台不同 PC
- angular - Angular - 错误 NG8002:无法绑定到“ngStyle”,因为它不是“div”的已知属性
- css - 字体真棒:如何使用常规样式图标?
- sql - sql查询添加列以选择视图
- java - Android MainActivity.java
- c++ - 抽象类、抽象方法参数和继承
- excel - 如何删除可变数量的行?
- r - 根据条件拆分数据帧
- linux - 通过 URL 参数限制 Haproxy 速率