这是哈希映射的有效单元测试吗?

时间:2019-02-05 15:19:09

标签: java unit-testing junit4

如果要以编写方式编写单元测试,我将无法理解。我有一个哈希图,用于存储客户记录。我正在尝试为我的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);

    }

2 个答案:

答案 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

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

  • 标识您编写的并且要测试的方法
  • 如果您的方法接受参数标识边界值,这可能会对您的代码造成问题(例如,对象的空值,列表的空列表,字符串的最大或最小整数) int)
  • 编写测试,以检查您的代码是否对这些特殊值起作用
  • 编写一个测试以检查其是否适用于正常值

如果一切正常,您可以按照mantra

尝试重新编写代码,使其重构以具有更好的设计。
  • RED -考虑您要开发的东西
  • 绿色-考虑如何通过测试
  • 重构-考虑如何改善现有的实施方式

然后添加新测试,然后再次执行红色,绿色和重构过程。