Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // AFTER REFACTORING:
- package org.legacy;
- import org.hamcrest.Matcher;
- import org.junit.Before;
- import org.junit.Test;
- import org.mockito.ArgumentMatcher;
- import org.mockito.Mockito;
- public class SupplyMonitorTest {
- private SupplyMonitor underTest;
- private Inventory inventory = Mockito.mock(Inventory.class);
- private SupplySystemWrapper supplySystem = Mockito.mock(SupplySystemWrapper.class);
- private Matcher<PurchaseOrder> orderMatcher = new ArgumentMatcher<PurchaseOrder>() {
- @Override
- public boolean matches(Object argument) {
- PurchaseOrder order = (PurchaseOrder) argument;
- return SupplyMonitor.PENCIL_ITEM_CODE.equals(order.getItemCode())
- && order.getQuantity() == 280;
- }
- };
- @Before
- public void setUp() throws Exception {
- underTest = new SupplyMonitor(inventory, 100, supplySystem);
- }
- @Test
- public void should_order_pencils_when_undersupplied() {
- Mockito.when(inventory.getItemCount(SupplyMonitor.PENCIL_ITEM_CODE)).thenReturn(120);
- underTest.trackAndProcurePencils();
- Mockito.verify(supplySystem).buy(Mockito.argThat(orderMatcher ), Mockito.any());
- }
- }
- //-------------------------------------------------------
- package org.legacy;
- public class SupplyMonitor {
- private static final int TARGET_PENCILS_PER_EMPLOYEE = 4;
- static final String PENCIL_ITEM_CODE = "123";
- private static final String CREDIT_CARD_NUMBER = "XXXX XXXX XXXX XXXX";
- private SupplySystemWrapper supplySystem;
- private Inventory inventory;
- private int currentEmployeeCount;
- // legacy constructor - to be deleted once all refererencing code has been
- // refactored
- public SupplyMonitor(Inventory inventory, int currentEmployeeCount) {
- super();
- this.inventory = inventory;
- this.currentEmployeeCount = currentEmployeeCount;
- // one new line to keep the old static call via the wrapper
- this.supplySystem = new SupplySystemWrapper() {
- };
- }
- // new constructor for tests
- public SupplyMonitor(Inventory inventory, int currentEmployeeCount, SupplySystemWrapper supplySystem) {
- super();
- this.supplySystem = supplySystem;
- this.inventory = inventory;
- this.currentEmployeeCount = currentEmployeeCount;
- }
- public void trackAndProcurePencils() {
- int targetPencilCount = this.currentEmployeeCount * TARGET_PENCILS_PER_EMPLOYEE;
- int currentPencilCount = inventory.getItemCount(PENCIL_ITEM_CODE);
- if (currentPencilCount < targetPencilCount) {
- // changed static call to wrapper call:
- this.supplySystem.buy(new PurchaseOrder(PENCIL_ITEM_CODE, targetPencilCount - currentPencilCount),
- new CreditCard(CREDIT_CARD_NUMBER));
- }
- }
- }
Add Comment
Please, Sign In to add comment