gpt4 book ai didi

Java自定义Exception错误未报告异常

转载 作者:行者123 更新时间:2023-12-02 02:12:50 26 4
gpt4 key购买 nike

您好,我在对异常引发函数运行 junit 测试时遇到一些问题,

我有一个定制的异常(exception):

package rental;
public class UnknownVehicleException extends Exception{
public UnknownVehicleException(){
System.out.println("Vehicule not found in agency");
}
}

以下是 RentalAgency 类的基础:

public class RentalAgency {
// vehicles of this agency
private List<Vehicle> theVehicles;

// maps client and rented vehicle (at most one vehicle by client)
private Map<Client,Vehicle> rentedVehicles;

public RentalAgency(List<Vehicle> theVehicles, Map<Client,Vehicle> rentedVehicles) {
this.theVehicles = theVehicles;
this.rentedVehicles = rentedVehicles;
}

这个函数应该在某些情况下抛出这个异常:

/** client rents a vehicle
* @param client the renter
* @param v the rented vehicle
* @return the daily rental price
* @exception UnknownVehicleException if v is not a vehicle of this agency
* @exception IllegalStateException if v is already rented or client rents already another vehicle
*/
public float rentVehicle(Client client, Vehicle v) throws UnknownVehicleException, IllegalStateException {
if(! this.theVehicles.contains(v)){
throw new UnknownVehicleException();
}
if(this.hasRentedAVehicle(client) || this.isRented(v)){
throw new IllegalStateException("Client is already renting a vehicle or the vehicle is already being rented");
}
else{
this.rentedVehicles.put(client, v);
return v.getDailyPrice();
}
}

现在有了所有这些,我正在尝试运行此测试:

@Test (expected = UnknownVehicleException.class)
public void testRentVehicleIfVehicleNotInAgency(){
this.renault.rentVehicle(this.client1, this.clio);
}

这给了我

unreported exception UnknownVehicleException; must be caught or declared to be thrown

我不知道我哪里搞砸了

感谢任何帮助,并随时询问有关我的代码的更多详细信息

最佳答案

您的测试方法不会引发或捕获异常。您期望出现异常,但实际上并未抛出异常。

@Test (expected = UnknownVehicleException.class)
public void testRentVehicleIfVehicleNotInAgency() throws UnknownVehicleException {
this.renault.rentVehicle(this.client1, this.clio);
}

关于Java自定义Exception错误未报告异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49719059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com