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!

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 return the desired output.

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.launchMockitoTestsAndPrint;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

class Main {
    public static void main(String[] args) {
        launchMockitoTestsAndPrint(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 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
        ____;
    }
}
Edit and Run Code