在Java中進行單元測試時,我們通常使用JUnit框架。當一個方法拋出異常時,我們可以使用@Test
注解的expected
屬性或者ExpectedException
規則來測試這個異常。下面是兩種方法的示例:
方法1:使用@Test
注解的expected
屬性
假設我們有一個方法divide
,當除數為0時,它會拋出一個ArithmeticException
異常:
public class Calculator {
public int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
}
為了測試這個異常,我們可以使用@Test
注解的expected
屬性:
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test(expected = ArithmeticException.class)
public void testDivideByZero() {
Calculator calculator = new Calculator();
calculator.divide(1, 0);
}
}
方法2:使用ExpectedException
規則
首先,需要在測試類中導入ExpectedException
規則:
import org.junit.Rule;
import org.junit.rules.ExpectedException;
然后,在測試類中聲明一個ExpectedException
實例:
public class CalculatorTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
}
接下來,在測試方法中使用expect
、expectMessage
等方法來定義預期的異常和異常消息:
@Test
public void testDivideByZero() {
Calculator calculator = new Calculator();
thrown.expect(ArithmeticException.class);
thrown.expectMessage("Division by zero");
calculator.divide(1, 0);
}
這兩種方法都可以用來測試拋出異常的情況。ExpectedException
規則提供了更多的靈活性,例如,你可以檢查異常的多個屬性,或者在同一個測試方法中檢查多個異常。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。