From e4337ef091521e09d91f535d236303a78560cdcc Mon Sep 17 00:00:00 2001 From: Peter Kofler Date: Tue, 13 Feb 2024 14:10:04 +0100 Subject: [PATCH] Replace Global Reference with Getter to control Singleton. --- .../codecop/dependencies/d/ShippingCost.java | 10 +++++--- .../dependencies/d/ShippingCostTest.java | 25 ++++++++++++++----- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/Java/src/main/java/org/codecop/dependencies/d/ShippingCost.java b/Java/src/main/java/org/codecop/dependencies/d/ShippingCost.java index db88bc3..14320af 100644 --- a/Java/src/main/java/org/codecop/dependencies/d/ShippingCost.java +++ b/Java/src/main/java/org/codecop/dependencies/d/ShippingCost.java @@ -5,11 +5,11 @@ public class ShippingCost { public Money calculate(Country country, DeliveryOptions options) { final Money cost; - if (RestCountriesAPI.getInstance().isInCommonMarket(country)) { + if (getRestApiInstance().isInCommonMarket(country)) { // flat rate in EU cost = new Money(5); - } else if (RestCountriesAPI.getInstance().isInAmericas(country)) { + } else if (getRestApiInstance().isInAmericas(country)) { // US & Canada & South American if (options == DeliveryOptions.EXPRESS) { cost = new Money(40); @@ -19,11 +19,15 @@ public Money calculate(Country country, DeliveryOptions options) { } else { // other countries, e.g. Asia - int km = RestCountriesAPI.getInstance().distanceTo(country); + int km = getRestApiInstance().distanceTo(country); cost = new Money(km).percentage(10); } return cost; } + protected RestCountriesAPI getRestApiInstance() { + return RestCountriesAPI.getInstance(); + } + } diff --git a/Java/src/test/java/org/codecop/dependencies/d/ShippingCostTest.java b/Java/src/test/java/org/codecop/dependencies/d/ShippingCostTest.java index 79533c9..50d86a8 100644 --- a/Java/src/test/java/org/codecop/dependencies/d/ShippingCostTest.java +++ b/Java/src/test/java/org/codecop/dependencies/d/ShippingCostTest.java @@ -1,15 +1,28 @@ package org.codecop.dependencies.d; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; public class ShippingCostTest { @Test - public void test4() { - ShippingCost shippingCost = new ShippingCost(); - - assertNotNull(shippingCost); + public void inEuropeanUnion() { + RestCountriesAPI restCountriesAPI = mock(RestCountriesAPI.class); + when(restCountriesAPI.isInCommonMarket(any(Country.class))).thenReturn(true); + ShippingCost shippingCost = new ShippingCost() { + @Override + protected RestCountriesAPI getRestApiInstance() { + return restCountriesAPI; + } + }; + + Money cost = shippingCost.calculate(new Country("AT"), DeliveryOptions.STANDARD); + + assertEquals(new Money(5), cost); + // 0 seconds :-( } }