java - 在数组中测试 "getCustomer"方法时,预期值和实际值应该是什么?

标签 java arrays unit-testing junit

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

我在顶部定义“customerList” 私有(private)列表 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;

    }
}

最佳答案

基于您使用的 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);
        });  
 }

关于java - 在数组中测试 "getCustomer"方法时,预期值和实际值应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55366062/

相关文章:

java - 更改引用而不显式更改其引用

java - 在 Java 中,捕获一般异常和特定异常(例如 IOException?)之间有什么区别?

javascript - 为什么 push() 在循环中不起作用?

java - 验证 JUnit 中的具体异常详细信息

c# - NUnit 无法识别包含数组的 TestCase

java - 后缀和 openJDK 11 : "No appropriate protocol (protocol is disabled or cipher suites are inappropriate)"

java.lang.Process Kill 未完成

java - 使用 okhttp 将文本和多个图像作为数组传递

java - java 获取二维数组中行和列的最大长度

unit-testing - 运行时记录 `cargo test`