Lab10 convert currency
In this lab, you'll have the GET method for your API return the price in GBP (Great British Pounds) instead of US Dollars, if a query parameter specifies it. For example:
http://localhost:8080/api/mealorder/1?currency=gbp
A. Create a Fake Currency Conversion Service¶
- Create a new interface
- Name:
CurrencyConversionService
- Package:
com.welltestedlearning.mealkiosk.domain
- Name:
- Add the following method to the interface:
int convertToGbp(int amount);
-
Create a new class that will implement the interface:
- Name:
FakeCurrencyConversionService
- Package:
com.welltestedlearning.mealkiosk.adapter
@Service public class FakeCurrencyConversionService implements CurrencyConversionService { public int convertToGbp(int amount) { return (int) (amount * 0.75); } }
- Name:
B. Use CurrencyService in API Controller¶
Injection¶
- Open the
MealOrderApiController
class - Inject the
CurrencyService
interface into the constructor- Remember, you don't create a new constructor, you add another parameter to the existing constructor.
- This will cause the
MealOrderApiControllerTest
tests to no longer compile, so fix them by passing in anew FakeCurrencyService()
instance.
Currency Query Parameter¶
-
Change the
findMealOrder()
method to accept an optional Query Parameter by changing the method signature to:This will assign any incoming Query Parameter (e.g.,public MealOrderResponse findMealOrder(@PathVariable("id") Long id, @RequestParam(value = "currency", defaultValue="usd") String currency) {
?currency=gbp
) to thecurrency
variable.The
defaultValue="usd"
means that if no query parameter exists,currency
will default to"usd"
.
Failing Test¶
- This will cause tests in
MealOrderApiControllerTest
to fail, so fix them by adding"usd"
as the second parameter to the tests that callfindMealOrder
. - Add this test to the
MealOrderApiControllerTest
:@Test public void getWithGbpQueryParamConvertsPriceToGbp() throws Exception { MealOrderRepository mealOrderRepository = new MealOrderRepository(); MealOrder mealOrder = MealBuilder.builder().burger("cheese").build(); MealOrder savedMealOrder = mealOrderRepository.save(mealOrder); MealOrderApiController controller = new MealOrderApiController(mealOrderRepository, DUMMY_KITCHEN_SERVICE, new FakeCurrencyService()); // When: we do a GET for the ID MealOrderResponse response = controller.findMealOrder(savedMealOrder.getId(), "gbp"); assertThat(response.getPrice()) .isEqualTo(4); // US$6 = GBP4 }
- This test should fail.
Fix the Test¶
- Add code near the end of the
findMealOrder
method: If thecurrency
string is "gbp", then:- Use the currency converter service to convert the
price
to GBP - Store that converted value into the meal order response (i.e.,
setPrice()
).
- Use the currency converter service to convert the
- Once you implement that properly, the test should now pass.