|
| 1 | +package com.baeldung.ddd.order.doubledispatch; |
| 2 | + |
| 3 | +import static org.assertj.core.api.Assertions.assertThat; |
| 4 | + |
| 5 | +import org.joda.money.CurrencyUnit; |
| 6 | +import org.joda.money.Money; |
| 7 | +import org.junit.jupiter.api.DisplayName; |
| 8 | +import org.junit.jupiter.api.Test; |
| 9 | + |
| 10 | +import com.baeldung.ddd.order.OrderFixtureUtils; |
| 11 | + |
| 12 | +public class DoubleDispatchDiscountPolicyUnitTest { |
| 13 | + // @formatter:off |
| 14 | + @DisplayName( |
| 15 | + "given regular order with items worth $100 total, " + |
| 16 | + "when apply 10% discount policy, " + |
| 17 | + "then cost after discount is $90" |
| 18 | + ) |
| 19 | + // @formatter:on |
| 20 | + @Test |
| 21 | + void test() throws Exception { |
| 22 | + // given |
| 23 | + Order order = new Order(OrderFixtureUtils.orderLineItemsWorthNDollars(100)); |
| 24 | + SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() { |
| 25 | + |
| 26 | + @Override |
| 27 | + public double discount(Order order) { |
| 28 | + return 0.10; |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public double discount(SpecialOrder order) { |
| 33 | + return 0; |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + // when |
| 38 | + Money totalCostAfterDiscount = order.totalCost(discountPolicy); |
| 39 | + |
| 40 | + // then |
| 41 | + assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 90)); |
| 42 | + } |
| 43 | + |
| 44 | + // @formatter:off |
| 45 | + @DisplayName( |
| 46 | + "given special order eligible for extra discount with items worth $100 total, " + |
| 47 | + "when apply 20% discount policy for extra discount orders, " + |
| 48 | + "then cost after discount is $80" |
| 49 | + ) |
| 50 | + // @formatter:on |
| 51 | + @Test |
| 52 | + void test1() throws Exception { |
| 53 | + // given |
| 54 | + boolean eligibleForExtraDiscount = true; |
| 55 | + Order order = new SpecialOrder(OrderFixtureUtils.orderLineItemsWorthNDollars(100), eligibleForExtraDiscount); |
| 56 | + SpecialDiscountPolicy discountPolicy = new SpecialDiscountPolicy() { |
| 57 | + |
| 58 | + @Override |
| 59 | + public double discount(Order order) { |
| 60 | + return 0; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public double discount(SpecialOrder order) { |
| 65 | + if (order.isEligibleForExtraDiscount()) |
| 66 | + return 0.20; |
| 67 | + return 0.10; |
| 68 | + } |
| 69 | + }; |
| 70 | + |
| 71 | + // when |
| 72 | + Money totalCostAfterDiscount = order.totalCost(discountPolicy); |
| 73 | + |
| 74 | + // then |
| 75 | + assertThat(totalCostAfterDiscount).isEqualTo(Money.of(CurrencyUnit.USD, 80.00)); |
| 76 | + } |
| 77 | +} |
0 commit comments