Get startedGet started for free

Unit test: Foreign exchange market

Let's practice creating and programming mocks in the banking context! Complete the unit test for the ExchangeApp, which uses the European Central Bank. As you're testing the convertEuroTo() logic, don't mock it. Instead, mock its dependency so that you can check if it works properly!

The necessary JUnit and Mockito packages have been imported for you.

This exercise is part of the course

Introduction to Testing in Java

View Course

Exercise instructions

  • Create a mock for the EuropeanCentralBankServer.
  • Use the correct syntax to program the mock to return 12345.0.
  • Verify the currency conversion returns the desired output.

Hands-on interactive exercise

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

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

class ExchangeAppTest {
    @Test
    void convertEuroTo_convertsTST() {
        // Create a mock object for the EuropeanCentralBankServer
        EuropeanCentralBankServer bank = ____(EuropeanCentralBankServer.class);
        ExchangeApp exchangeApp = new ExchangeApp(bank);
        double euroAmount = 100;
        // Stub the mock to return a value for given input
        ____(exchangeApp.convertEuroTo("TST", 100)).____(12345.0);

        double tstAmount = exchangeApp.convertEuroTo("TST", euroAmount);

        System.out.println("Converted " + euroAmount + " EUR to " + tstAmount + " TST.");
        // Assert on the exact expected value of tstAmount
        ____(1234500, ____);
    }
}
Edit and Run Code