嗨,我在针对异常引发功能运行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);
}
关于java - Java自定义异常错误未报告的异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49719059/