外匯:錯誤情境
EuropeanCentralBankServer 函式庫的文件指出,若嘗試轉換成該銀行未提供的貨幣,會拋出以下例外:
new RuntimeException("Currency not in ECB list: " + currencyName)
撰寫一個整合測試,驗證此錯誤情境。
本練習屬於課程
Java 測試入門
練習說明
- 補上正確的斷言,驗證拋出的例外是
RuntimeException的實例。 - 使用正確的斷言來檢查相等性。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class Main {
public static void main(String[] args) {
launchTestsAndPrint(ExchangeAppTest.class);
}
}
class ExchangeAppTest {
@Test
void convert_throwsException_whenGetRateThrowsException() {
EuropeanCentralBankServer bank = new EuropeanCentralBankServer();
ExchangeApp exchangeApp = new ExchangeApp(bank);
Exception expectedException = null;
try {
double result = exchangeApp.convertEuroTo("Invalid Currency", 1000);
} catch (Exception e) {
expectedException = e;
}
// Assert that the exception is an instance of the correct class
____(RuntimeException.class, expectedException);
// Assert that the exception message is correct
____("Currency not in ECB list: Invalid Currency", expectedException.getMessage());
}
}