这是 Hash Map 的有效单元测试吗?

Is this a valid unit test for 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 作者,目前您正在对此 class 进行单元测试。
所以不,你没有以正确的方式测试你的代码。
您想要的单元测试是 您的 class 的 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
}

当您编写单元测试时,您是在测试您编写的代码单元

测试中

@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

要编写好的单元测试,您需要:

  • 确定您编写的方法并希望测试。
  • 如果您的方法接受参数确定可能会给您的代码带来问题的边界值(例如对象的空值、列表的空列表、最大值或 int 的最小整数)
  • 写一个测试来检查你的代码是否有效那些特殊值
  • 写一个测试检查它是否适用于正常值

如果一切正常,您可以尝试重写代码重构它以获得更好的设计,遵循 mantra

  • RED - 想想你要开发什么
  • 绿色 - 思考如何让你的测试通过
  • Refactor - 思考如何改进现有的实现

然后添加新测试并再次遵循流程红色、绿色、重构。