首页 > 解决方案 > 这是 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);

    }

标签: javaunit-testingjunit4

解决方案


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
}

推荐阅读