การแลกเปลี่ยนเงินตราต่างประเทศ: กรณีเกิดข้อผิดพลาด
เอกสารของไลบรารี EuropeanCentralBankServer ระบุว่าหากพยายามแปลงสกุลเงินที่ธนาคารไม่รองรับ จะเกิด exception ดังนี้:
new RuntimeException("Currency not in ECB list: " + currencyName)
ให้เขียน integration test เพื่อตรวจสอบกรณีเกิดข้อผิดพลาดนี้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทดสอบใน Java เบื้องต้น
คำแนะนำการฝึกหัด
- เติม assertion ที่ถูกต้องเพื่อตรวจสอบว่า exception เป็น instance ของ
RuntimeException - ใช้ assertion ที่ถูกต้องสำหรับการตรวจสอบความเท่ากัน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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());
}
}