การแปลงสกุลเงิน
คุณกำลังทำงานบนแพลตฟอร์มซื้อขายสกุลเงิน โดยมีคลาส utility สำหรับแปลงค่าระหว่างสกุลเงิน เมธอด convert() ซึ่งเป็น public จะรับจำนวนเงินในสกุลเงินแรกและอัตราแลกเปลี่ยน แล้วคืนค่าเป็นสกุลเงินอื่น
งานของคุณคือเพิ่มข้อกำหนดของโปรเจกต์นี้เข้าไปในโค้ดเบสด้วยการเขียนเทสต์ จุดเริ่มต้นที่ดีคือการเขียน unit test สำหรับสถานการณ์ที่สำเร็จของเมธอดนี้
แพ็กเกจ JUnit ที่จำเป็นได้ถูก import ไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทดสอบใน Java เบื้องต้น
คำแนะนำการฝึกหัด
- เรียกใช้เมธอด
convert()โดยระบุสกุลเงินและอัตราแลกเปลี่ยน - ใช้ assertion ของ JUnit ที่เหมาะสมเพื่อตรวจสอบว่าค่า
convertedCurrencyเท่ากับค่าที่คาดหวัง
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class CurrencyConverterWithTests {
public static void main(String[] args) {
launchTestsAndPrint(CurrencyConverterTest.class);
}
}
class CurrencyConverter {
public static double convert(double currency, double exchangeRate) {
return currency * exchangeRate;
}
}
class CurrencyConverterTest {
@Test
void convert_returnsConvertedCurrency_whenValidInputs() {
double currency = 100;
double exchangeRate = 1.2;
// Call the convert method with the currency and exchange rate
double convertedCurrency = CurrencyConverter.____(currency, ____);
// Use the correct JUnit assertion, the expected value, and the converted currency amount
____(120, ____);
}
}