開始使用免費開始

貨幣換算

你正在開發一個貨幣交易平臺。有一個工具類別用來在不同貨幣間換算。它的公開方法 convert() 會接收第一種貨幣的金額與匯率,並回傳換算成另一種貨幣的數值。

你的任務是把專案需求以測試的形式納入程式碼庫。好的起點是先為此方法的成功情境撰寫一個單元測試。

所需的 JUnit 套件已為你匯入。

本練習屬於課程

Java 測試入門

檢視課程

練習說明

  • 以貨幣金額與匯率呼叫 convert() 方法。
  • 使用正確的 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, ____); 
    }
}
編輯並執行程式碼