Skip to content

Commit

Permalink
Replace global reference with getter to control singleton.
Browse files Browse the repository at this point in the history
  • Loading branch information
codecop committed Feb 13, 2024
1 parent 1a8f7f1 commit 55372d6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
10 changes: 7 additions & 3 deletions Java/src/main/java/org/codecop/dependencies/d/ShippingCost.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ public class ShippingCost {
public Money calculate(Country country, DeliveryOptions options) {
final Money cost;

if (RestCountriesAPI.getInstance().isInCommonMarket(country)) {
if (getRestCountriesInstance().isInCommonMarket(country)) {
// flat rate in EU
cost = new Money(5);

} else if (RestCountriesAPI.getInstance().isInAmericas(country)) {
} else if (getRestCountriesInstance().isInAmericas(country)) {
// US & Canada & South American
if (options == DeliveryOptions.EXPRESS) {
cost = new Money(40);
Expand All @@ -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 = getRestCountriesInstance().distanceTo(country);
cost = new Money(km).percentage(10);
}

return cost;
}

protected RestCountriesAPI getRestCountriesInstance() {
return RestCountriesAPI.getInstance();
}

}
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
package org.codecop.dependencies.d;

import org.junit.Test;
import static org.junit.Assert.assertEquals;
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 inEuropeanMarket() {
RestCountriesAPI restCountriesAPI = mock(RestCountriesAPI.class);
when(restCountriesAPI.isInCommonMarket(new Country("AT"))).thenReturn(true);
ShippingCost shippingCost = new ShippingCost() {
@Override
protected RestCountriesAPI getRestCountriesInstance() {
return restCountriesAPI;
}
};

Money cost = shippingCost.calculate(new Country("AT"), DeliveryOptions.STANDARD);

assertEquals(new Money(5), cost);
// 3 seconds :-(
}
}

0 comments on commit 55372d6

Please sign in to comment.