簡體   English   中英

Java Junit - 預計會拋出異常,但會拋出異常

[英]Java Junit - Expected Exception to be thrown but noting is thrown

在我的測試用例中引發了“預期的異常被拋出,但什么都沒有”被拋出。 如何解決這個問題。 如果在找到階乘時數字為負,我想拋出異常,

測試文件:-

public void testCalculateFactorialWithOutOfRangeException(){

    Factorial factorial = new Factorial();
    assertThrows(OutOfRangeException.class, () -> factorial.calculateFactorial(-12));
}

代碼文件 -

public class Factorial {

    public String calculateFactorial(int number){

    //If the number is less than 1
    try {
        if(number < 1)
            throw new OutOfRangeException("Number cannot be less than 1");
        if(number > 1000)
            throw new OutOfRangeException("Number cannot be greater than 1000");

    }
}

catch (OutOfRangeException e) {

}

class OutOfRangeException extends Exception {

    public OutOfRangeException(String str) {
        super(str);
    }
}

我預計 output 會成功,但它會導致失敗

您的測試很好,問題在於您的代碼沒有拋出異常,或者更正確地 - 拋出並捕獲它。

從方法中刪除catch (OutOfRangeException e)子句並添加throws OutOfRangeException然后您的測試將通過

當您的方法拋出異常時,您可以擁有如下所示的測試用例。

@Test(expected =OutOfRangeException.class)
public void testCalculateFactorialWithOutOfRangeException() throws OutOfRangeException{

    Factorial factorial = new Factorial();
   factorial.calculateFactorial(-12);
}

但是,在您的情況下,您不會在 class 中拋出異常,而是在 catch 塊中處理它,如果您在方法中拋出異常,那么它將起作用。

class Factorial {

    public String calculateFactorial(int number) throws OutOfRangeException{

        //If the number is less than 1

        if(number < 1)
            throw new OutOfRangeException("Number cannot be less than 1");
        if(number > 1000)
            throw new OutOfRangeException("Number cannot be greater than 1000");


        return "test";
   }
}

暫無
暫無

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

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