簡體   English   中英

Java自定義異常錯誤未報告的異常

[英]Java custom Exception error unreported exception

嗨,我在針對異常引發功能運行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; 必須被抓住或宣布被拋出

我不知道我在哪里搞砸了

任何幫助表示贊賞,並隨時要求我的代碼更多詳細信息

您的測試方法不會引發或捕獲異常。 您期望出現異常,但實際上不拋出異常。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM