如果要以编写方式编写单元测试,我将无法理解。我有一个哈希图,用于存储客户记录。我正在尝试为我的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);
}
答案 0 :(得分:1)
您不是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
}
答案 1 :(得分:0)
编写单元测试时,您将测试编写的代码单元。
测试中
@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
。
要编写好的单元测试,您需要:
如果一切正常,您可以按照mantra
尝试重新编写代码,使其重构以具有更好的设计。然后添加新测试,然后再次执行红色,绿色和重构过程。