【问题标题】:What should be expected and actual values when testing the "getCustomer" method in the array?测试数组中的“getCustomer”方法时,预期值和实际值应该是多少?
【发布时间】:2019-03-26 20:56:27
【问题描述】:

我有两个问题要问你。我将测试方法添加到代码行。测试方法的“预期”和“实际”值应该是多少?以及如何使用 try-catch 或任何东西在测试方法中真正测试我的自定义异常?你能帮忙吗?

I define "customerList" on top 私有列表 customerList=new ArrayList();



`````````There is a "getCustomer" method in the "Bank" class`````````

public Customer getCustomer(int ID) throws CustomerNotFoundException {

        for (int i = 0; i < customerList.size(); i++) {
            if (customerList.get(i).getId() == ID) {
                return customerList.get(i);
            }
        }
        throw new CustomerNotFoundException(ID);
    }
```````

`````````There is a "addCustomer" method`````````

public void addCustomer(int id, String name){
        customerList.add(new Customer(name, id));
    }

`````````There is a "getCustomer" test that I ask`````````

/** Test getCustomer()**/
    @Test public void tc504_Bank(){
        try {
            Bank b = new Bank("Test Name", "Test Address");
            b.addCustomer(1, "Test Name");
            b.getCustomer(1);
            Assert.assertEquals("Customer Not Found", b.getCustomerList().get(0), ??? );
        }catch (CustomerNotFoundException e){
            Assert.assertEquals("PIN not all digits", 0, 1);
        }
    }
````````

`````````There is a custom expection class````````

public class CustomerNotFoundException extends RuntimeException {
    private String name;
    private int id;

    public CustomerNotFoundException(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public CustomerNotFoundException(String name) {
        this.name = name;
    }

    public CustomerNotFoundException(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "CustomerNotFoundException: id - " + id + " name - " + name;

    }
}

【问题讨论】:

    标签: java arrays unit-testing junit


    【解决方案1】:

    根据您使用的 junit 库版本:

    JUnit4

     @Test(expected = CustomerNotFoundException.class) 
     public void tc504_Bank(){
            Bank b = new Bank("Test Name", "Test Address");
            b.addCustomer(1, "Test Name");
            b.getCustomer(1);
     }
    

    JUnit5

     @Test public void tc504_Bank(){
            Bank b = new Bank("Test Name", "Test Address");
            b.addCustomer(1, "Test Name");
            assertThrows(CustomerNotFoundException.class, () -> {
                b.getCustomer(1);
            });  
     }
    

    【讨论】:

    • 对不起,我迟到了。谢谢您的帮助。它奏效了。
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    相关资源
    最近更新 更多