简体   繁体   中英

Java custom Exception error unreported exception

Hi I'm having some issue while running junit tests on exception raising functions,

I have a custom made exception :

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

Here are the basis of the RentalAgency class :

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

and this function, supposed to throw this exception on certain cases :

/** 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();
      }
    }

So now with all of these, I'm trying to run this test :

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

which gives me

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

and I can't figure out where did I messed up

Any help appreciated and feel free to ask for more details on my code

Your test method doesn't throw or catch the exception. You expect the exception but don't actually throw it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM