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

时间:2018-04-08 14:40:27

标签: java exception junit

嗨,我在异常提升函数上运行junit测试时遇到了一些问题,

我有一个自定义异常:

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);
}

给了我

  

未报告的异常UnknownVehicleException;必须被抓住或   宣布被抛出

我无法弄清楚我搞砸了哪里

任何帮助表示感谢,并随时可以询问有关我的代码的详细信息

1 个答案:

答案 0 :(得分:2)

您的测试方法不会抛出或捕获异常。你期望异常,但实际上并不抛弃它。

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