Java 如何在测试用例中处理用户指定的异常
我以前写过一个完整的成功程序,包括7个类(Java 如何在测试用例中处理用户指定的异常,java,exception,arraylist,exception-handling,throws,Java,Exception,Arraylist,Exception Handling,Throws,我以前写过一个完整的成功程序,包括7个类(Date,Address,Time,Customer,InClassCourse,OnLineCourse),一个接口(Invoice),当然还有测试类(CustomerTest)。接口Invoice有一个方法createInvoice,该方法在Customer类中实现。在测试案例中,我创建了3个新客户,添加了他们各自的课程,然后根据他们注册的课程数量、他们注册的课程类型以及课程是InClassCourse还是OnLineCourse,计算他们的费用,最
Date
,Address
,Time
,Customer
,InClassCourse
,OnLineCourse
),一个接口(Invoice
),当然还有测试类(CustomerTest
)。接口Invoice
有一个方法createInvoice
,该方法在Customer
类中实现。在测试案例中,我创建了3个新客户,添加了他们各自的课程,然后根据他们注册的课程数量、他们注册的课程类型以及课程是InClassCourse
还是OnLineCourse
,计算他们的费用,最后在对话框中打印信息。客户和课程列表保存在两个单独的数组列表中:
ArrayList<Customer> customerList = new ArrayList<Customer>();
ArrayList<Course> courseList = new ArrayList<Course>();
createInvoice方法如下所示:
public String createInvoice() throws CustomerNotEnrolledException
{
if((courseList == null) || (this.courseList.isEmpty()))
{
throw new CustomerNotEnrolledException();
}
double total;
if (cType==CustomerType.STUDENT)
total = 25;
else if (cType==CustomerType.FACULTY)
total = 50;
else if (cType==CustomerType.GOVERNMENT)
total = 35;
else
total = 0;
for(Course course:this.courseList)
{
total += course.calculateCharge(this.cType);
}
return (String.format("%s\t\t%d\t\t$%.2f", this.name,
this.accountNumber,total));
}
请明确你的问题。我如何编写代码来检查我的异常,我猜它将在try块中?你不检查异常。如果适用,您可以
抛出它,然后尝试捕获它。首先执行。这是您创建的自定义异常。因此,现在您必须决定在抛出代码时应该如何反应。
public String createInvoice() throws CustomerNotEnrolledException
{
if((courseList == null) || (this.courseList.isEmpty()))
{
throw new CustomerNotEnrolledException();
}
double total;
if (cType==CustomerType.STUDENT)
total = 25;
else if (cType==CustomerType.FACULTY)
total = 50;
else if (cType==CustomerType.GOVERNMENT)
total = 35;
else
total = 0;
for(Course course:this.courseList)
{
total += course.calculateCharge(this.cType);
}
return (String.format("%s\t\t%d\t\t$%.2f", this.name,
this.accountNumber,total));
}