gpt4 book ai didi

java - 这是 HashMap 的有效单元测试吗?

转载 作者:行者123 更新时间:2023-12-02 10:18:01 25 4
gpt4 key购买 nike

我试图了解我是否以写入方式编写单元测试。我有一个 HashMap ,用于存储我的客户注册。我正在尝试为我的 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
}

关于java - 这是 HashMap 的有效单元测试吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com