Get startedGet started for free

Foreign Exchange: Error scenario

The documentation for the EuropeanCentralBankServer library says that attempting to convert to currencies the bank doesn't offer will result in this exception:

new RuntimeException("Currency not in ECB list: " + currencyName)

Write an integration test that verifies this error scenario.

This exercise is part of the course

Introduction to Testing in Java

View Course

Exercise instructions

  • Fill in the correct assertion to verify the exception is an instance of RuntimeException.
  • Use the correct assertion to check equality.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import org.junit.jupiter.api.Test;
import com.datacamp.util.api.banking.EuropeanCentralBankServer;

import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchTestsAndPrint;
import static org.junit.jupiter.api.Assertions.*;

class Main {
    public static void main(String[] args) {
        launchTestsAndPrint(ExchangeAppTest.class);
    }
}

class ExchangeApp {
    private EuropeanCentralBankServer bank;

    public ExchangeApp(EuropeanCentralBankServer bank) {
        this.bank = bank;
    }

    public double convertEuroTo(String currency, double amount) {
        double rate = this.bank.getRateEuroTo(currency);

        return amount * rate;
    }
}

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());
    }
}
Edit and Run Code