CommencerCommencer gratuitement

Unit test: Foreign exchange exceptions

One possible error scenario for the exchange app is the bank server being unavailable due to an outage or network issues. To insure against disruptive exceptions, you have coded in a try/catch inside the convertEuroTo method.

Simulate the error scenario by making the mock EuropeanCentralBankServer object throw an exception when a rate is requested.

Cet exercice fait partie du cours

Introduction to Testing in Java

Afficher le cours

Instructions

  • Make the mock bank object throw an exception when getRateEuroTo is called.
  • Create the exact exception object you want to simulate.
  • Verify the convertEuroTo method does not throw an exception but returns -1 in this scenario.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de 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) {
        try {
        	double rate = this.bank.getRateEuroTo(currency);
            
            return amount * rate;
        } catch (Exception e) {
        	System.out.println("Could not get exchange rate: " + e.getMessage());
            return -1;
        }
    }
}

class ExchangeAppTest {
    @Test
    void convertEuroTo_throwsException_whenBankUnavailable() {
        EuropeanCentralBankServer bank = mock(EuropeanCentralBankServer.class);
        ExchangeApp exchangeApp = new ExchangeApp(bank);
        double euroAmount = 450;
        // Stub the mock to throw an exception
        when(exchangeApp.convertEuroTo("TST", 100)).____(____("Bank server is unavailable."));
        
        double tstAmount = exchangeApp.convertEuroTo("TST", euroAmount);

		// Assert on the return value of the method
		____;
    }
}
Modifier et exécuter le code