Building the Currency Converter
We’re about to move from toy examples into something a bit more realistic — a component that talks to an external API and returns a result.
But before we write any tests, we need to build the component itself.
We’re going to create a class called CurrencyConverter
. It will:
- Accept an amount and two currencies (like "GBP" to "USD")
- Use a service to get the exchange rate
- Return the converted amount
We’ll test this in multiple ways over the next few lessons — including error handling, mocking, spying, and using data providers.
Let’s set the foundation.
Where to put the code
We’ll continue working in the same project as before. No need to start from scratch again.
To keep things organized, we’ll place this new code in a subfolder called RealWorld
.
Inside your src/
and tests/
folders, create these two new directories:
src/RealWorld/ tests/RealWorld/
All of our real-world code will live in those folders.
Step 1: Create the ExchangeRateService interface
Start by creating an interface called ExchangeRateService
. This will define how we fetch exchange rates — and it will let us easily mock the behavior later when we test.
Step 2: Create the CurrencyConverter
The CurrencyConverter
will use this interface to fetch the exchange rate, then multiply it by the given amount.
In the next lesson, we’ll write our first test for this converter — and learn how to mock a dependency so we can test it without calling a real API.
0 comments