method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ProductDetailsListenersT { public final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } String productNumber = product.getStringField(NUMBER); if (productNumber == null) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("productNumber", applyInOperator(productNumber)); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; view.redirectTo(url, false, true, parameters); } final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showTechnologiesWithUsingProduct(final ViewDefinitionState view, final ComponentState state,
final String[] args); }### Answer:
@Test public void shouldntShowTechnologiesWithProductIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithProduct(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldntShowTechnologiesWithProductIfProductIsntSavedAndProductNameIsNull() { given(product.getId()).willReturn(1L); given(product.getStringField(NAME)).willReturn(null); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithProduct(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldShowTechnologiesWithProductIfProductIsSavedAndProductNameIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(L_PRODUCT_NUMBER); filters.put("productNumber", "["+ L_PRODUCT_NUMBER + "]"); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologies"); String url = "../page/technologies/technologiesList.html"; productDetailsListenersT.showTechnologiesWithProduct(view, null, null); verify(view).redirectTo(url, false, true, parameters); } |
### Question:
ProductDetailsViewHooksT { public void updateRibbonState(final ViewDefinitionState view) { Entity loggedUser = dataDefinitionService .get(QcadooSecurityConstants.PLUGIN_IDENTIFIER, QcadooSecurityConstants.MODEL_USER) .get(securityService.getCurrentUserId()); if (!securityService.hasRole(loggedUser, "ROLE_TECHNOLOGIES")) { view.getComponentByReference("technologyTab").setVisible(false); } FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonGroup technologies = (RibbonGroup) window.getRibbon().getGroupByName("technologies"); RibbonActionItem showTechnologiesWithTechnologyGroup = (RibbonActionItem) technologies .getItemByName("showTechnologiesWithTechnologyGroup"); RibbonActionItem showTechnologiesWithProduct = (RibbonActionItem) technologies .getItemByName("showTechnologiesWithProduct"); if (product.getId() != null) { Entity technologyGroup = product.getBelongsToField("technologyGroup"); if (technologyGroup == null) { updateButtonState(showTechnologiesWithTechnologyGroup, false); } else { updateButtonState(showTechnologiesWithTechnologyGroup, true); } updateButtonState(showTechnologiesWithProduct, true); return; } updateButtonState(showTechnologiesWithTechnologyGroup, false); updateButtonState(showTechnologiesWithProduct, false); } void updateRibbonState(final ViewDefinitionState view); }### Answer:
@Test @Ignore public void shouldntUpdateRibbonStateIfProductIsntSaved() { given(product.getId()).willReturn(null); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("technologies")).willReturn(technologies); given(technologies.getItemByName("showTechnologiesWithTechnologyGroup")).willReturn(showTechnologiesWithTechnologyGroup); given(technologies.getItemByName("showTechnologiesWithProduct")).willReturn(showTechnologiesWithProduct); productDetailsViewHooksT.updateRibbonState(view); verify(showTechnologiesWithTechnologyGroup).setEnabled(false); verify(showTechnologiesWithProduct).setEnabled(false); }
@Test @Ignore public void shouldUpdateRibbonStateIfProductIsSavedAndTechnologyGroupIsNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(null); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("technologies")).willReturn(technologies); given(technologies.getItemByName("showTechnologiesWithTechnologyGroup")).willReturn(showTechnologiesWithTechnologyGroup); given(technologies.getItemByName("showTechnologiesWithProduct")).willReturn(showTechnologiesWithProduct); productDetailsViewHooksT.updateRibbonState(view); verify(showTechnologiesWithTechnologyGroup).setEnabled(false); verify(showTechnologiesWithProduct).setEnabled(true); }
@Ignore @Test public void shouldUpdateRibbonStateIfProductIsSavedAndTechnologyGroupIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(technologyGroup); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("technologies")).willReturn(technologies); given(technologies.getItemByName("showTechnologiesWithTechnologyGroup")).willReturn(showTechnologiesWithTechnologyGroup); given(technologies.getItemByName("showTechnologiesWithProduct")).willReturn(showTechnologiesWithProduct); productDetailsViewHooksT.updateRibbonState(view); verify(showTechnologiesWithTechnologyGroup).setEnabled(true); verify(showTechnologiesWithProduct).setEnabled(true); } |
### Question:
TechnologyGroupDetailsViewHooks { public void addTechnologyGroupToProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent technologyGroupForm = (FormComponent) view.getComponentByReference("form"); Entity technologyGroup = technologyGroupForm.getEntity(); if (technologyGroup.getId() == null) { return; } FormComponent productForm = (FormComponent) view.getComponentByReference("product"); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } product = getProductFromDB(product.getId()); product.setField("technologyGroup", technologyGroup); product.getDataDefinition().save(product); } void addTechnologyGroupToProduct(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); }### Answer:
@Test public void shouldntAddTechnologyGroupToProductIfTechnologyGroupIsntSaved() { given(technologyGroup.getId()).willReturn(null); technologyGroupDetailsViewHooks.addTechnologyGroupToProduct(view, null, null); verify(product, never()).setField("technologyGroup", technologyGroup); verify(productDD, never()).save(product); }
@Test public void shouldntAddTechnologyGroupToProductIfTechnologyGroupIsSavedAndProductIsNull() { given(technologyGroup.getId()).willReturn(L_ID); given(product.getId()).willReturn(null); technologyGroupDetailsViewHooks.addTechnologyGroupToProduct(view, null, null); verify(product, never()).setField("technologyGroup", technologyGroup); verify(productDD, never()).save(product); }
@Test public void shouldAddTechnologyGroupToProductIfTechnologyGroupIsSavedAndProductIsntNull() { given(technologyGroup.getId()).willReturn(L_ID); given(product.getId()).willReturn(L_ID); given(product.getDataDefinition()).willReturn(productDD); given(dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_PRODUCT)).willReturn(productDD); given(productDD.get(L_ID)).willReturn(product); technologyGroupDetailsViewHooks.addTechnologyGroupToProduct(view, null, null); verify(product).setField("technologyGroup", technologyGroup); verify(productDD).save(product); } |
### Question:
TechnologyTreeValidators { public boolean checkConsumingTheSameProductFromManySubOperations(final DataDefinition technologyDD, final Entity technology, final boolean autoCloseMessage) { Entity techFromDB = technologyDD.get(technology.getId()); EntityTree tree = techFromDB.getTreeField(TechnologyFields.OPERATION_COMPONENTS); Map<String, Set<Entity>> nodesMap = technologyTreeValidationService .checkConsumingTheSameProductFromManySubOperations(tree); for (Entry<String, Set<Entity>> entry : nodesMap.entrySet()) { String parentNodeNumber = entry.getKey(); for (Entity product : entry.getValue()) { String productName = product.getStringField(ProductFields.NAME); String productNumber = product.getStringField(ProductFields.NUMBER); technology.addGlobalError( "technologies.technology.validate.global.error.subOperationsProduceTheSameProductThatIsConsumed", autoCloseMessage, parentNodeNumber, productName, productNumber); } } return nodesMap.isEmpty(); } boolean invalidateIfWrongFormula(final DataDefinition dataDefinition, final Entity entity); boolean checkConsumingTheSameProductFromManySubOperations(final DataDefinition technologyDD, final Entity technology,
final boolean autoCloseMessage); boolean invalidateIfBelongsToAcceptedTechnology(final DataDefinition dataDefinition, final Entity entity); }### Answer:
@Test public void shouldAddMessagesCorrectly() { String messageKey = "technologies.technology.validate.global.error.subOperationsProduceTheSameProductThatIsConsumed"; String parentNode = "1."; String productName = "name"; String productNumber = "abc123"; Long techId = 1L; given(technology.getStringField("state")).willReturn("02accepted"); given(technology.getId()).willReturn(techId); given(techDataDefinition.get(techId)).willReturn(technology); given(technology.getTreeField("operationComponents")).willReturn(tree); given(product.getStringField("name")).willReturn(productName); given(product.getStringField("number")).willReturn(productNumber); Map<String, Set<Entity>> nodesMap = Maps.newHashMap(); Set<Entity> productSet = Sets.newHashSet(); productSet.add(product); nodesMap.put("1.", productSet); given(technologyTreeValidationService.checkConsumingTheSameProductFromManySubOperations(tree)).willReturn(nodesMap); technologyTreeValidators.checkConsumingTheSameProductFromManySubOperations(techDataDefinition, technology, true); Mockito.verify(technology).addGlobalError(messageKey, true, parentNode, productName, productNumber); } |
### Question:
CostNormsForOperationService { public void fillCurrencyFields(final ViewDefinitionState view) { String currencyStringCode = currencyService.getCurrencyAlphabeticCode(); FieldComponent component = null; for (String componentReference : Sets.newHashSet("pieceworkCostCURRENCY", "laborHourlyCostCURRENCY", "machineHourlyCostCURRENCY")) { component = (FieldComponent) view.getComponentByReference(componentReference); if (component == null) { continue; } component.setFieldValue(currencyStringCode); component.requestComponentUpdateState(); } } void copyCostValuesFromOperation(final ViewDefinitionState view, final ComponentState operationLookupState,
final String[] args); void inheritOperationNormValues(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); void fillCurrencyFields(final ViewDefinitionState view); void copyCostNormsToTechnologyOperationComponent(final DataDefinition dd, final Entity technologyOperationComponent); }### Answer:
@Test public void shouldFillCurrencyFields() throws Exception { String currency = "PLN"; when(currencyService.getCurrencyAlphabeticCode()).thenReturn(currency); when(view.getComponentByReference("pieceworkCostCURRENCY")).thenReturn(field1); when(view.getComponentByReference("laborHourlyCostCURRENCY")).thenReturn(field2); when(view.getComponentByReference("machineHourlyCostCURRENCY")).thenReturn(field3); costNormsForOperationService.fillCurrencyFields(view); Mockito.verify(field1).setFieldValue(currency); Mockito.verify(field2).setFieldValue(currency); Mockito.verify(field3).setFieldValue(currency); } |
### Question:
StockCorrectionModelValidators { public boolean validateStockCorrection(final DataDefinition stockCorrectionDD, final Entity stockCorrection) { Entity location = stockCorrection.getBelongsToField(LOCATION); if (location != null) { String locationType = location.getStringField(TYPE); if (!CONTROL_POINT.getStringValue().equals(locationType)) { stockCorrection.addError(stockCorrectionDD.getField(LOCATION), "materialFlow.validate.global.error.locationIsNotSimpleControlPoint"); return false; } } return true; } boolean validateStockCorrection(final DataDefinition stockCorrectionDD, final Entity stockCorrection); boolean checkIfLocationHasExternalNumber(final DataDefinition stockCorrectionDD, final Entity stockCorrection); }### Answer:
@Test public void shouldReturnFalseAndAddErrorWhenValidateStockCorrectionIfLocationIsntNullAndLocationTypeIsntControlPoint() { given(stockCorrection.getBelongsToField(LOCATION)).willReturn(location); given(location.getStringField(TYPE)).willReturn("otherLocation"); boolean result = stockCorrectionModelValidators.validateStockCorrection(stockCorrectionDD, stockCorrection); assertFalse(result); verify(stockCorrection).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnTrueWhenValidateStockCorrectionIfLocationIsntNullAndLocationTypeIsControlPoint() { given(stockCorrection.getBelongsToField(LOCATION)).willReturn(location); given(location.getStringField(TYPE)).willReturn(CONTROL_POINT.getStringValue()); boolean result = stockCorrectionModelValidators.validateStockCorrection(stockCorrectionDD, stockCorrection); assertTrue(result); verify(stockCorrection, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnTrueWhenValidateStockCorrectionIfLocationIsNull() { given(stockCorrection.getBelongsToField(LOCATION)).willReturn(null); boolean result = stockCorrectionModelValidators.validateStockCorrection(stockCorrectionDD, stockCorrection); assertTrue(result); verify(stockCorrection, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } |
### Question:
ProductionLinesServiceImpl implements ProductionLinesService { @Override public Integer getWorkstationTypesCount(final Entity operationComponent, final Entity productionLine) { List<Entity> workstationTypeComponents = productionLine.getHasManyField(ProductionLineFields.WORKSTATION_TYPE_COMPONENTS); Entity desiredWorkstation = operationComponent.getBelongsToField(TechnologyOperationComponentFields.OPERATION) .getBelongsToField(OperationFields.WORKSTATION_TYPE); if (desiredWorkstation != null) { for (Entity workstationTypeComponent : workstationTypeComponents) { Entity workstation = workstationTypeComponent.getBelongsToField(OperationFields.WORKSTATION_TYPE); if (desiredWorkstation.getId().equals(workstation.getId())) { return (Integer) workstationTypeComponent.getField(WorkstationTypeComponentFields.QUANTITY); } } } return productionLine.getIntegerField(ProductionLineFields.QUANTITY_FOR_OTHER_WORKSTATION_TYPES); } @Override Integer getWorkstationTypesCount(final Entity operationComponent, final Entity productionLine); @Override Integer getWorkstationTypesCount(final Long productionLineId, final String workstationTypeNumber); }### Answer:
@Test public void shouldReturnCorrectWorkstationCount() { given(operation.getBelongsToField("workstationType")).willReturn(work2); Integer workstationCount = productionLinesServiceImpl.getWorkstationTypesCount(opComp1, productionLine); assertEquals(Integer.valueOf(234), workstationCount); }
@Test public void shouldReturnSpecifiedQuantityIfNoWorkstationIsFound() { given(productionLine.getIntegerField("quantityForOtherWorkstationTypes")).willReturn(456); given(operation.getBelongsToField("workstationType")).willReturn(work3); Integer workstationCount = productionLinesServiceImpl.getWorkstationTypesCount(opComp1, productionLine); assertEquals(Integer.valueOf(456), workstationCount); } |
### Question:
TechnologyDataProviderImpl implements TechnologyDataProvider { public Optional<Entity> tryFind(final Long id) { return Optional.ofNullable(id).map(i -> getDataDefinition().get(i)); } Optional<Entity> tryFind(final Long id); }### Answer:
@Test public final void shouldReturnTechnology() { Entity technologyFromDb = mockEntity(); stubDataDefGetResult(technologyFromDb); Optional<Entity> res = technologyDataProvider.tryFind(1L); Assert.assertEquals(Optional.of(technologyFromDb), res); }
@Test public final void shouldReturnEmptyIfIdIsMissing() { Optional<Entity> res = technologyDataProvider.tryFind(null); Assert.assertEquals(Optional.<Entity> empty(), res); }
@Test public final void shouldReturnEmptyIfEntityCannotBeFound() { stubDataDefGetResult(null); Optional<Entity> res = technologyDataProvider.tryFind(1L); Assert.assertEquals(Optional.<Entity> empty(), res); } |
### Question:
TechnologyNameAndNumberGenerator { public String generateNumber(final Entity product) { String numberPrefix = product.getField(ProductFields.NUMBER) + "-"; return numberGeneratorService.generateNumberWithPrefix(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY, 3, numberPrefix); } String generateNumber(final Entity product); String generateName(final Entity product); }### Answer:
@Test public final void shouldGenerateNumber() { Entity product = mockEntity(); stubStringField(product, ProductFields.NUMBER, "SomeProductNumber"); technologyNameAndNumberGenerator.generateNumber(product); verify(numberGeneratorService).generateNumberWithPrefix(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY, 3, "SomeProductNumber-"); } |
### Question:
TechnologyNameAndNumberGenerator { public String generateName(final Entity product) { LocalDate date = LocalDate.now(); String currentDateString = String.format("%s.%s", date.getYear(), date.getMonthValue()); String productName = product.getStringField(ProductFields.NAME); String productNumber = product.getStringField(ProductFields.NUMBER); return translationService.translate("technologies.operation.name.default", LocaleContextHolder.getLocale(), productName, productNumber, currentDateString); } String generateNumber(final Entity product); String generateName(final Entity product); }### Answer:
@Test public final void shouldGenerateName() { String productNumber = "SomeProductNumber"; String productName = "Some product name"; Entity product = mockEntity(); stubStringField(product, ProductFields.NUMBER, productNumber); stubStringField(product, ProductFields.NAME, productName); technologyNameAndNumberGenerator.generateName(product); LocalDate date = LocalDate.now(); String expectedThirdArgument = String.format("%s.%s", date.getYear(), date.getMonthValue()); verify(translationService).translate("technologies.operation.name.default", LocaleContextHolder.getLocale(), productName, productNumber, expectedThirdArgument); } |
### Question:
OperationProductComponentImpl implements InternalOperationProductComponent { @Override public void setField(final String name, final Object value) { entity.setField(name, value); } OperationProductComponentImpl(final OperationCompType operationType, final DataDefinition opcDataDef); @Override void setField(final String name, final Object value); @Override Entity getWrappedEntity(); @Override void setProduct(final Entity product); @Override void setQuantity(final BigDecimal quantity); @Override void setPriority(final int priority); }### Answer:
@Test public final void shouldThrowExceptionWhenTryToAddProductWithIncorrectTypeToOutputProductComponent() { performWrongTypeProductTest(buildOpoc()); verify(wrappedEntity, Mockito.never()).setField(OperationProductInComponentFields.PRODUCT, product); }
@Test public final void shouldThrowExceptionWhenTryToAddProductWithIncorrectTypeToInputProductComponent() { performWrongTypeProductTest(buildOpic()); verify(wrappedEntity, Mockito.never()).setField(OperationProductOutComponentFields.PRODUCT, product); }
@Test public final void shouldNotThrowExceptionWhenAddingProductWithCorrectTypeToOutputProductComponent() { performCorrectTypeProductTest(buildOpoc()); verify(wrappedEntity).setField(OperationProductOutComponentFields.PRODUCT, product); }
@Test public final void shouldNotThrowExceptionWhenAddingProductWithCorrectTypeToInputProductComponent() { performCorrectTypeProductTest(buildOpic()); verify(wrappedEntity).setField(OperationProductInComponentFields.PRODUCT, product); } |
### Question:
TechnologyTreeValidationServiceImpl implements TechnologyTreeValidationService { @Override public Map<String, Set<Entity>> checkConsumingTheSameProductFromManySubOperations(final EntityTree technologyTree) { Map<String, Set<Entity>> parentToProductsMap = Maps.newHashMap(); if (technologyTree != null && !technologyTree.isEmpty()) { final EntityTreeNode rootNode = technologyTree.getRoot(); collectChildrenProducingTheSameParentInputs(parentToProductsMap, rootNode); } return parentToProductsMap; } @Override final Map<String, Set<String>> checkConsumingManyProductsFromOneSubOp(final EntityTree technologyTree); @Override Map<String, Set<Entity>> checkConsumingTheSameProductFromManySubOperations(final EntityTree technologyTree); }### Answer:
@Test public final void shouldReturnNotEmptyMapIfSubOpsProduceTheSameOutputsWhichAreConsumed() { Entity product1 = mockProductComponent(1L); Entity product2 = mockProductComponent(2L); Entity product3 = mockProductComponent(3L); Entity product4 = mockProductComponent(4L); Entity product5 = mockProductComponent(5L); Entity product6 = mockProductComponent(6L); EntityTreeNode node3 = mockOperationComponent(3L, "3.", newArrayList(product5), newArrayList(product2, product3)); EntityTreeNode node2 = mockOperationComponent(2L, "2.", newArrayList(product6), newArrayList(product2, product4)); EntityTreeNode node1 = mockOperationComponent(1L, "1.", newArrayList(product2), newArrayList(product1), newArrayList(node2, node3)); given(tree.getRoot()).willReturn(node1); Map<String, Set<Entity>> returnedMap = technologyTreeValidationService .checkConsumingTheSameProductFromManySubOperations(tree); assertNotNull(returnedMap); assertFalse(returnedMap.isEmpty()); assertEquals(1, returnedMap.size()); assertTrue(returnedMap.containsKey("1.")); assertTrue(returnedMap.get("1.").contains(product2)); } |
### Question:
TransformationsModelValidators { public boolean checkIfTransfersAreValid(final DataDefinition transformationsDD, final Entity transformations) { List<Entity> transfersConsumption = transformations.getHasManyField(TRANSFERS_CONSUMPTION); List<Entity> transfersProduction = transformations.getHasManyField(TRANSFERS_PRODUCTION); Iterable<Boolean> validationResults = Lists.newArrayList(areTransfersValid(transfersConsumption), areTransfersValid(transfersProduction), checkIfTransfersNumbersAreDistinct(transfersConsumption, transfersProduction), checkIfTransfersNumbersAreDistinct(transfersProduction, transfersConsumption)); return Iterables.all(validationResults, Predicates.equalTo(true)); } boolean checkIfTransfersAreValid(final DataDefinition transformationsDD, final Entity transformations); boolean checkIfLocationFromOrLocationToHasExternalNumber(final DataDefinition transformationDD,
final Entity transformation); }### Answer:
@Test public void shouldReturnFalseWhenCheckIfTransfersAreValidAndTransfersArentNull() { Entity transferConsumption = mockTransfer(null, null, null); Entity transferProduction = mockTransfer(null, null, null); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption)); stubHasManyField(transformations, TRANSFERS_PRODUCTION, Lists.newArrayList(transferProduction)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertFalse(result); }
@Test public void shouldReturnFalseWhenCheckIfTransfersAreValidAndTransferProductAlreadyAdded() { Entity transferConsumption1 = mockTransfer(L_NUMBER_CONSUMPTION_1, productConsumption, BigDecimal.ONE); Entity transferConsumption2 = mockTransfer(L_NUMBER_CONSUMPTION_2, productProduction, BigDecimal.ONE); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption1, transferConsumption2)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertFalse(result); }
@Test public void shouldReturnFalseWhenCheckIfTransfersAreValidAndTransfersNumersArentDistinct() { Entity transferConsumption1 = mockTransfer(L_NUMBER_CONSUMPTION_1, productConsumption, BigDecimal.ONE); Entity transferConsumption2 = mockTransfer(L_NUMBER_CONSUMPTION_1, productProduction, BigDecimal.ONE); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption1, transferConsumption2)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertFalse(result); }
@Test public void shouldReturnTrueWhenCheckIfTransfersAreValidAndTransfersArentNull() { Entity transferConsumption = mockTransfer(L_NUMBER_CONSUMPTION_1, productProduction, BigDecimal.ONE); Entity transferProduction = mockTransfer(L_NUMBER_PRODUCTION_1, productProduction, BigDecimal.ONE); stubHasManyField(transformations, TRANSFERS_CONSUMPTION, Lists.newArrayList(transferConsumption)); stubHasManyField(transformations, TRANSFERS_PRODUCTION, Lists.newArrayList(transferProduction)); boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertTrue(result); }
@Test public void shouldReturnTrueWhenCheckIfTransfersAreValidAndAllTransfersAreNull() { boolean result = transformationsModelValidators.checkIfTransfersAreValid(transformationsDD, transformations); assertTrue(result); } |
### Question:
TechnologyService { public BigDecimal getProductCountForOperationComponent(final Entity operationComponent) { return getMainOutputProductComponent(operationComponent).getDecimalField(L_QUANTITY); } void copyCommentAndAttachmentFromLowerInstance(final Entity technologyOperationComponent, final String belongsToName); boolean checkIfTechnologyStateIsOtherThanCheckedAndAccepted(final Entity technology); boolean isTechnologyUsedInActiveOrder(final Entity technology); void loadProductsForReferencedTechnology(final ViewDefinitionState viewDefinitionState, final ComponentState state,
final String[] args); void generateTechnologyGroupNumber(final ViewDefinitionState viewDefinitionState); void generateTechnologyNumber(final ViewDefinitionState view, final ComponentState state, final String[] args); void generateTechnologyName(final ViewDefinitionState view, final ComponentState state, final String[] args); void setLookupDisableInTechnologyOperationComponent(final ViewDefinitionState viewDefinitionState); void toggleDetailsViewEnabled(final ViewDefinitionState view); String getProductType(final Entity product, final Entity technology); void addOperationsFromSubtechnologiesToList(final EntityTree entityTree,
final List<Entity> technologyOperationComponents); boolean invalidateIfAllreadyInTheSameOperation(final DataDefinition operationProductComponentDD,
final Entity operationProductComponent); Optional<Entity> tryGetMainOutputProductComponent(Entity technologyOperationComponent); Entity getMainOutputProductComponent(Entity technologyOperationComponent); BigDecimal getProductCountForOperationComponent(final Entity operationComponent); boolean isExternalSynchronized(final Long technologyId); boolean isIntermediateProduct(final Entity opic); boolean isFinalProduct(final Entity opoc); static final String L_01_COMPONENT; static final String L_02_INTERMEDIATE; static final String L_03_FINAL_PRODUCT; static final String L_04_WASTE; static final String L_00_UNRELATED; }### Answer:
@Test public void shouldReturnOutputProductCountForOperationComponent() { BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); }
@Test public void shouldThrowAnExceptionIfThereAreNoProductsOrIntermediates() { EntityList opComp2prodOuts = mockEntityIterator(asList(prodOutComp2)); when(opComp2.getHasManyField("operationProductOutComponents")).thenReturn(opComp2prodOuts); try { technologyService.getProductCountForOperationComponent(opComp2); fail(); } catch (IllegalStateException e) { } }
@Test public void shouldReturnOutputProductCountForOperationComponentAlsoForTechnologyInstanceOperationComponent() { when(dataDefinition.getName()).thenReturn("technologyInstanceOperationComponent"); when(opComp2.getBelongsToField("technologyOperationComponent")).thenReturn(opComp2); when(opComp1.getBelongsToField("technologyOperationComponent")).thenReturn(opComp1); BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); }
@Test public void shouldReturnOutputProductCountForOperationComponentAlsoForReferenceTechnology() { when(opComp2.getStringField("entityType")).thenReturn("referenceTechnology"); Entity refTech = mock(Entity.class); when(opComp2.getBelongsToField("referenceTechnology")).thenReturn(refTech); EntityTree tree = mock(EntityTree.class); when(refTech.getTreeField("operationComponents")).thenReturn(tree); when(tree.getRoot()).thenReturn(opComp2); BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); }
@Test public void shouldReturnOutputProductCountForOperationComponentAlsoIfParentOperationIsNull() { when(opComp2.getBelongsToField("parent")).thenReturn(null); when(prodOutComp2.getBelongsToField("product")).thenReturn(product2); when(prodOutComp1.getBelongsToField("product")).thenReturn(product1); when(technology.getBelongsToField("product")).thenReturn(product2); BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2); assertEquals(new BigDecimal(10), count); } |
### Question:
OrderDetailsListenersPPS { public void redirectToProductionPerShift(final ViewDefinitionState view, final ComponentState state, final String[] args) { Long orderId = (Long) state.getFieldValue(); if (orderId == null) { return; } Long ppsId = ppsHelper.getPpsIdForOrder(orderId); if (ppsId == null) { ppsId = ppsHelper.createPpsForOrderAndReturnId(orderId); Preconditions.checkNotNull(ppsId); } redirect(view, ppsId); } void redirectToProductionPerShift(final ViewDefinitionState view, final ComponentState state, final String[] args); }### Answer:
@Test public void shouldRedirectToProductionPerShiftView() { Long givenOrderId = 1L; Long expectedPpsId = 50L; given(state.getFieldValue()).willReturn(givenOrderId); given(ppsHelper.getPpsIdForOrder(givenOrderId)).willReturn(expectedPpsId); orderDetailsListenersPPS.redirectToProductionPerShift(view, state, new String[] {}); verifyRedirectToPpsDetails(expectedPpsId); }
@Test public void shouldRedirectToJustCreatedProductionPerShiftView() { Long givenOrderId = 1L; Long expectedPpsId = 50L; given(state.getFieldValue()).willReturn(givenOrderId); given(ppsHelper.getPpsIdForOrder(givenOrderId)).willReturn(null); given(ppsHelper.createPpsForOrderAndReturnId(givenOrderId)).willReturn(expectedPpsId); orderDetailsListenersPPS.redirectToProductionPerShift(view, state, new String[] {}); verifyRedirectToPpsDetails(expectedPpsId); }
@Test public void shouldThrowExceptionIfProductionPerShiftCanNotBeSaved() { Long givenOrderId = 1L; given(state.getFieldValue()).willReturn(givenOrderId); given(ppsHelper.getPpsIdForOrder(givenOrderId)).willReturn(null); given(ppsHelper.createPpsForOrderAndReturnId(givenOrderId)).willReturn(null); try { orderDetailsListenersPPS.redirectToProductionPerShift(view, state, new String[] {}); Assert.fail(); } catch (NullPointerException ex) { } } |
### Question:
LineChangeoverNormsHooks { public boolean checkUniqueNorms(final DataDefinition changeoverNormDD, final Entity changeoverNorm) { SearchCriteriaBuilder searchCriteriaBuilder = dataDefinitionService .get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS) .find() .add(SearchRestrictions.belongsTo(FROM_TECHNOLOGY, changeoverNorm.getBelongsToField(FROM_TECHNOLOGY))) .add(SearchRestrictions.belongsTo(TO_TECHNOLOGY, changeoverNorm.getBelongsToField(TO_TECHNOLOGY))) .add(SearchRestrictions.belongsTo(FROM_TECHNOLOGY_GROUP, changeoverNorm.getBelongsToField(FROM_TECHNOLOGY_GROUP))) .add(SearchRestrictions.belongsTo(TO_TECHNOLOGY_GROUP, changeoverNorm.getBelongsToField(TO_TECHNOLOGY_GROUP))) .add(SearchRestrictions.belongsTo(PRODUCTION_LINE, changeoverNorm.getBelongsToField(PRODUCTION_LINE))); if (changeoverNorm.getId() != null) { searchCriteriaBuilder.add(SearchRestrictions.ne("id", changeoverNorm.getId())); } Entity existingChangeoverNorm = searchCriteriaBuilder.uniqueResult(); if (existingChangeoverNorm != null) { changeoverNorm.addGlobalError(L_LINE_CHANGEOVER_NORMS_LINE_CHANGEOVER_NORM_NOT_UNIQUE, existingChangeoverNorm.getStringField(NUMBER)); return false; } return true; } boolean checkUniqueNorms(final DataDefinition changeoverNormDD, final Entity changeoverNorm); boolean checkRequiredField(final DataDefinition changeoverNormDD, final Entity changeoverNorm); }### Answer:
@Test public void shouldAddErrorForEntityWhenNotUnique() { Long id = 1L; String changeoverNumber = "0002"; given(changeoverNorm.getId()).willReturn(id); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY)).willReturn(fromTechnology); given(changeoverNorm.getBelongsToField(TO_TECHNOLOGY)).willReturn(toTechnology); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY_GROUP)).willReturn(fromTechnologyGroup); given(changeoverNorm.getBelongsToField(TO_TECHNOLOGY_GROUP)).willReturn(toTechnologyGroup); given(changeoverNorm.getBelongsToField(PRODUCTION_LINE)).willReturn(productionLine); given( dataDefinitionService.get(LineChangeoverNormsConstants.PLUGIN_IDENTIFIER, LineChangeoverNormsConstants.MODEL_LINE_CHANGEOVER_NORMS)).willReturn(changeoverNormDD); given(changeoverNormDD.find()).willReturn(searchCriteria); searchMatchingChangeroverNorms(fromTechnology, toTechnology, fromTechnologyGroup, toTechnologyGroup, productionLine); given(searchCriteria.uniqueResult()).willReturn(changeover); given(changeover.getStringField(NUMBER)).willReturn(changeoverNumber); hooks.checkUniqueNorms(changeoverNormDD, changeoverNorm); verify(changeoverNorm).addGlobalError("lineChangeoverNorms.lineChangeoverNorm.notUnique", changeoverNumber); } |
### Question:
PpsCorrectionReasonAppender { public Either<String, Entity> append(final ProductionPerShiftId ppsId, final PpsCorrectionReason reason) { if (ppsId == null) { return Either.left("Missing pps id!"); } if (reason == null || StringUtils.isBlank(reason.get())) { return Either.left("Missing or blank reason type value!"); } return trySave(createCorrectionReason(ppsId, reason)); } @Autowired PpsCorrectionReasonAppender(final DataDefinitionService dataDefinitionService); Either<String, Entity> append(final ProductionPerShiftId ppsId, final PpsCorrectionReason reason); }### Answer:
@Test public final void shouldFailDueToMissingPpsId() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(null, CORRECTION_REASON); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing pps id!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); }
@Test public final void shouldFailDueToMissingReason() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, null); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); }
@Test public final void shouldFailDueToMissingReasonValue() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, new PpsCorrectionReason(null)); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); }
@Test public final void shouldFailDueToEmptyReasonValue() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, new PpsCorrectionReason("")); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); }
@Test public final void shouldFailDueToBlankReasonValue() { Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, new PpsCorrectionReason(" ")); Assert.assertTrue(res.isLeft()); Assert.assertEquals("Missing or blank reason type value!", res.getLeft()); verify(correctionReasonDataDef, never()).save(newlyCreatedReasonEntity); }
@Test public final void shouldFailDueToValidationErrors() { Entity invalidEntity = mockEntity(null, correctionReasonDataDef); given(invalidEntity.isValid()).willReturn(false); given(correctionReasonDataDef.save(anyEntity())).willReturn(invalidEntity); Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, CORRECTION_REASON); Assert.assertTrue(res.isLeft()); String expectedMsg = String.format("Cannot save %s.%s because of validation errors", ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_REASON_TYPE_OF_CORRECTION_PLAN); Assert.assertEquals(expectedMsg, res.getLeft()); verify(correctionReasonDataDef, times(1)).save(newlyCreatedReasonEntity); }
@Test public final void shouldAppendReason() { Entity validSavedEntity = mockEntity(null, correctionReasonDataDef); given(validSavedEntity.isValid()).willReturn(true); given(correctionReasonDataDef.save(anyEntity())).willReturn(validSavedEntity); Either<String, Entity> res = ppsCorrectionReasonAppender.append(PPS_ID, CORRECTION_REASON); Assert.assertTrue(res.isRight()); Assert.assertEquals(validSavedEntity, res.getRight()); verify(correctionReasonDataDef, times(1)).save(newlyCreatedReasonEntity); verify(newlyCreatedReasonEntity).setField(ReasonTypeOfCorrectionPlanFields.PRODUCTION_PER_SHIFT, PPS_ID.get()); verify(newlyCreatedReasonEntity).setField(ReasonTypeOfCorrectionPlanFields.REASON_TYPE_OF_CORRECTION_PLAN, CORRECTION_REASON.get()); } |
### Question:
PPSReportHooks { public boolean checkIfIsMoreThatFiveDays(final DataDefinition reportDD, final Entity report) { int days = ppsReportXlsHelper.getNumberOfDaysBetweenGivenDates(report); if (days > 7) { report.addError(reportDD.getField(PPSReportFields.DATE_FROM), "productionPerShift.report.onlyFiveDays"); report.addError(reportDD.getField(PPSReportFields.DATE_TO), "productionPerShift.report.onlyFiveDays"); return false; } return true; } boolean checkIfIsMoreThatFiveDays(final DataDefinition reportDD, final Entity report); final boolean validateDates(final DataDefinition reportDD, final Entity report); void clearGenerated(final DataDefinition reportDD, final Entity report); }### Answer:
@Test public void shouldReturnFalseWhenCheckIfIsMoreThatFiveDays() { given(ppsReportXlsHelper.getNumberOfDaysBetweenGivenDates(report)).willReturn(10); boolean result = hooks.checkIfIsMoreThatFiveDays(reportDD, report); Assert.assertFalse(result); verify(report, times(2)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnTrueWhenCheckIfIsMoreThatFiveDays() { given(ppsReportXlsHelper.getNumberOfDaysBetweenGivenDates(report)).willReturn(3); boolean result = hooks.checkIfIsMoreThatFiveDays(reportDD, report); Assert.assertTrue(result); verify(report, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } |
### Question:
PPSReportHooks { public void clearGenerated(final DataDefinition reportDD, final Entity report) { report.setField(PPSReportFields.GENERATED, false); report.setField(PPSReportFields.FILE_NAME, null); } boolean checkIfIsMoreThatFiveDays(final DataDefinition reportDD, final Entity report); final boolean validateDates(final DataDefinition reportDD, final Entity report); void clearGenerated(final DataDefinition reportDD, final Entity report); }### Answer:
@Test public void shouldClearGenerated() { hooks.clearGenerated(reportDD, report); verify(report, times(2)).setField(Mockito.anyString(), Mockito.any()); } |
### Question:
PPSReportDetailsHooks { public void disableFields(final ViewDefinitionState view) { FormComponent form = (FormComponent) view.getComponentByReference(L_FORM); Long reportId = form.getEntityId(); if (reportId == null) { setFieldsState(view, REPORT_FIELDS, true); } else { Entity report = getReportFromDb(reportId); if (report != null) { boolean generated = report.getBooleanField(PPSReportFields.GENERATED); if (generated) { setFieldsState(view, REPORT_FIELDS, false); } else { setFieldsState(view, REPORT_FIELDS, true); } } } } void generateReportNumber(final ViewDefinitionState view); void disableFields(final ViewDefinitionState view); }### Answer:
@Test public void shouldntDisableFieldsWhenEntityIsntSaved() { given(view.getComponentByReference(L_FORM)).willReturn(reportForm); given(view.getComponentByReference(PPSReportFields.NUMBER)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.NAME)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_FROM)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_TO)).willReturn(fieldComponent); given(reportForm.getEntityId()).willReturn(null); hooks.disableFields(view); verify(fieldComponent, times(4)).setEnabled(true); }
@Test public void shouldntDisableFieldsWhenEntityIsSavedAndReportIsntGenerated() { given(view.getComponentByReference(L_FORM)).willReturn(reportForm); given(view.getComponentByReference(PPSReportFields.NUMBER)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.NAME)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_FROM)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_TO)).willReturn(fieldComponent); given(reportForm.getEntityId()).willReturn(1L); given(dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PPS_REPORT)).willReturn(reportDD); given(reportDD.get(1L)).willReturn(report); given(report.getBooleanField(PPSReportFields.GENERATED)).willReturn(false); hooks.disableFields(view); verify(fieldComponent, times(4)).setEnabled(true); }
@Test public void shouldDisableFieldsWhenEntityIsSavedAndReportIsGenerated() { given(view.getComponentByReference(L_FORM)).willReturn(reportForm); given(view.getComponentByReference(PPSReportFields.NUMBER)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.NAME)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_FROM)).willReturn(fieldComponent); given(view.getComponentByReference(PPSReportFields.DATE_TO)).willReturn(fieldComponent); given(reportForm.getEntityId()).willReturn(1L); given(dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PPS_REPORT)).willReturn(reportDD); given(reportDD.get(1L)).willReturn(report); given(report.getBooleanField(PPSReportFields.GENERATED)).willReturn(true); hooks.disableFields(view); verify(fieldComponent, times(4)).setEnabled(false); } |
### Question:
ProductionPerShiftDetailsHooks { void fillTechnologyOperationLookup(final ViewDefinitionState view, final Entity technology) { LookupComponent technologyOperationLookup = (LookupComponent) view.getComponentByReference(OPERATION_LOOKUP_REF); for (Entity rootOperation : technologyOperationDataProvider.findRoot(technology.getId()).asSet()) { technologyOperationLookup.setFieldValue(rootOperation.getId()); technologyOperationLookup.requestComponentUpdateState(); } technologyOperationLookup.setEnabled(true); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view,
final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }### Answer:
@Test public void shouldAddRootForOperation() throws Exception { final Long rootOperationId = 2L; LookupComponent technologyOperationLookup = mockLookup(mockEntity()); stubViewComponent(OPERATION_LOOKUP_REF, technologyOperationLookup); Entity rootOperation = mockEntity(rootOperationId); given(technologyOperationDataProvider.findRoot(anyLong())).willReturn(Optional.of(rootOperation)); productionPerShiftDetailsHooks.fillTechnologyOperationLookup(view, technology); verify(technologyOperationLookup).setFieldValue(rootOperationId); } |
### Question:
ProductionPerShiftDetailsHooks { void setupProgressTypeComboBox(final ViewDefinitionState view, final OrderState orderState, final ProgressType progressType) { FieldComponent plannedProgressType = (FieldComponent) view.getComponentByReference(PROGRESS_TYPE_COMBO_REF); plannedProgressType.setFieldValue(progressType.getStringValue()); plannedProgressType.requestComponentUpdateState(); plannedProgressType.setEnabled(orderState != OrderState.PENDING); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view,
final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }### Answer:
@Test public void shouldEnabledPlannedProgressTypeForInProgressOrder() throws Exception { ProgressType progressType = ProgressType.PLANNED; productionPerShiftDetailsHooks.setupProgressTypeComboBox(view, OrderState.IN_PROGRESS, progressType); verify(progressTypeComboBox).setFieldValue(progressType.getStringValue()); verify(progressTypeComboBox).setEnabled(true); } |
### Question:
ProductionPerShiftDetailsHooks { void fillOrderDateComponents(final ViewDefinitionState view, final Entity order) { for (ImmutableMap.Entry<String, String> modelFieldToViewReference : ORDER_DATE_FIELDS_TO_VIEW_COMPONENTS.entrySet()) { FieldComponent dateComponent = (FieldComponent) view.getComponentByReference(modelFieldToViewReference.getValue()); Date date = order.getDateField(modelFieldToViewReference.getKey()); dateComponent.setFieldValue(DateUtils.toDateTimeString(date)); dateComponent.requestComponentUpdateState(); } } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view,
final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }### Answer:
@Test public void shouldSetOrderStartDatesWhenPlannedDateExists() throws Exception { ComponentState plannedDateField = mockFieldComponent(null); ComponentState correctedDateField = mockFieldComponent(null); ComponentState effectiveDateField = mockFieldComponent(null); stubViewComponent(PLANNED_START_DATE_TIME_REF, plannedDateField); stubViewComponent(CORRECTED_START_DATE_TIME_REF, correctedDateField); stubViewComponent(EFFECTIVE_START_DATE_TIME_REF, effectiveDateField); Date planned = new Date(); stubDateField(order, OrderFields.DATE_FROM, planned); stubDateField(order, OrderFields.CORRECTED_DATE_FROM, null); stubDateField(order, OrderFields.EFFECTIVE_DATE_FROM, null); productionPerShiftDetailsHooks.fillOrderDateComponents(view, order); verify(plannedDateField).setFieldValue(DateUtils.toDateTimeString(planned)); verify(correctedDateField).setFieldValue(""); verify(effectiveDateField).setFieldValue(""); }
@Test public void shouldSetOrderStartDatesWhenPlannedAndCorrectedDateExists() throws Exception { ComponentState plannedDateField = mockFieldComponent(null); ComponentState correctedDateField = mockFieldComponent(null); ComponentState effectiveDateField = mockFieldComponent(null); stubViewComponent(PLANNED_START_DATE_TIME_REF, plannedDateField); stubViewComponent(CORRECTED_START_DATE_TIME_REF, correctedDateField); stubViewComponent(EFFECTIVE_START_DATE_TIME_REF, effectiveDateField); Date planned = new Date(); Date corrected = new Date(); Date effective = new Date(); stubDateField(order, OrderFields.DATE_FROM, planned); stubDateField(order, OrderFields.CORRECTED_DATE_FROM, corrected); stubDateField(order, OrderFields.EFFECTIVE_DATE_FROM, effective); productionPerShiftDetailsHooks.fillOrderDateComponents(view, order); verify(plannedDateField).setFieldValue(DateUtils.toDateTimeString(planned)); verify(correctedDateField).setFieldValue(DateUtils.toDateTimeString(corrected)); verify(effectiveDateField).setFieldValue(DateUtils.toDateTimeString(effective)); } |
### Question:
ProductionPerShiftDetailsHooks { public void setProductAndFillProgressForDays(final ViewDefinitionState view) { Entity order = getEntityFromLookup(view, "order").get(); OrderState orderState = OrderState.of(order); ProgressType progressType = resolveProgressType(view); AwesomeDynamicListComponent progressForDaysADL = (AwesomeDynamicListComponent) view .getComponentByReference(PROGRESS_ADL_REF); setProductAndFillProgressForDays(view, progressForDaysADL, orderState, progressType); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view,
final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }### Answer:
@Test public void shouldFillProgressesADL() throws Exception { Entity technologyOperation = mockEntity(3L); stubViewComponent(OPERATION_LOOKUP_REF, mockLookup(technologyOperation)); LookupComponent producedProductLookup = mockLookup(null); stubViewComponent(PRODUCED_PRODUCT_LOOKUP_REF, producedProductLookup); long productId = 100L; Entity product = mockEntity(productId); stubMainTocProduct(product); stubProgressType(ProgressType.CORRECTED); stubOrderState(OrderState.PENDING); Entity firstPfd = mockEntity(); Entity secondPfd = mockEntity(); stubProgressForDayDataProviderFindForOp(technologyOperation, true, Lists.newArrayList(firstPfd, secondPfd)); String productUnit = "someArbitraryUnit"; stubStringField(product, ProductFields.UNIT, productUnit); FieldComponent firstDayField = mockFieldComponent(null); LookupComponent firstShiftLookup = mockLookup(mockEntity()); FieldComponent firstQuantityFieldComponent = mockFieldComponent(null); FieldComponent firstUnitFieldComponent = mockFieldComponent(null); FormComponent firstPfdForm = mockProgressForDayRowForm(firstDayField, firstShiftLookup, firstQuantityFieldComponent, firstUnitFieldComponent); FieldComponent secondDayField = mockFieldComponent(null); LookupComponent secondShiftLookup = mockLookup(mockEntity()); FieldComponent secondQuantityFieldComponent = mockFieldComponent(null); FieldComponent secondUnitFieldComponent = mockFieldComponent(null); FormComponent secondPfdForm = mockProgressForDayRowForm(secondDayField, secondShiftLookup, secondQuantityFieldComponent, secondUnitFieldComponent); AwesomeDynamicListComponent progressesAdl = mock(AwesomeDynamicListComponent.class); stubViewComponent("progressForDays", progressesAdl); given(progressesAdl.getFormComponents()).willReturn(Lists.newArrayList(firstPfdForm, secondPfdForm)); productionPerShiftDetailsHooks.setProductAndFillProgressForDays(view); verify(progressesAdl).setFieldValue(Lists.newArrayList(firstPfd, secondPfd)); verify(producedProductLookup).setFieldValue(productId); verify(firstUnitFieldComponent).setFieldValue(productUnit); verify(secondUnitFieldComponent).setFieldValue(productUnit); } |
### Question:
ProductionPerShiftDetailsHooks { void disableComponents(final AwesomeDynamicListComponent progressForDaysADL, final ProgressType progressType, final OrderState orderState) { boolean isEnabled = (progressType == ProgressType.CORRECTED || orderState == OrderState.PENDING) && !UNSUPPORTED_ORDER_STATES.contains(orderState); for (FormComponent progressForDaysForm : progressForDaysADL.getFormComponents()) { progressForDaysForm.setFormEnabled(isEnabled); AwesomeDynamicListComponent dailyProgressADL = (AwesomeDynamicListComponent) progressForDaysForm .findFieldComponentByName(DAILY_PROGRESS_ADL_REF); for (FormComponent dailyProgressForm : dailyProgressADL.getFormComponents()) { Entity dpEntity = dailyProgressForm.getPersistedEntityWithIncludedFormValues(); boolean isLocked = dpEntity.getBooleanField(DailyProgressFields.LOCKED); dailyProgressForm.setFormEnabled(isEnabled && !isLocked); } dailyProgressADL.setEnabled(isEnabled); } progressForDaysADL.setEnabled(isEnabled); } void onBeforeRender(final ViewDefinitionState view); ProgressType resolveProgressType(final ViewDefinitionState view); void disableReasonOfCorrection(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view); boolean isCorrectedPlan(final ViewDefinitionState view); void setProductAndFillProgressForDays(final ViewDefinitionState view,
final AwesomeDynamicListComponent progressForDaysADL, final OrderState orderState, final ProgressType progressType); }### Answer:
@Test public void shouldDisableDailyProgressRowsForLockedEntities() { FormComponent firstPfdFirstDailyForm = mockForm(mockEntity()); FormComponent firstPfdSecondDailyForm = mockForm(mockLockedEntity()); AwesomeDynamicListComponent firstPfdDailyAdl = mock(AwesomeDynamicListComponent.class); given(firstPfdDailyAdl.getFormComponents()).willReturn( Lists.newArrayList(firstPfdFirstDailyForm, firstPfdSecondDailyForm)); FormComponent firstPfdForm = mockForm(mockEntity()); stubFormComponent(firstPfdForm, DAILY_PROGRESS_ADL_REF, firstPfdDailyAdl); FormComponent secondPfdFirstDailyForm = mockForm(mockEntity()); AwesomeDynamicListComponent secondPfdDailyAdl = mock(AwesomeDynamicListComponent.class); given(secondPfdDailyAdl.getFormComponents()).willReturn(Lists.newArrayList(secondPfdFirstDailyForm)); FormComponent secondPfdForm = mockForm(mockEntity()); stubFormComponent(secondPfdForm, DAILY_PROGRESS_ADL_REF, secondPfdDailyAdl); AwesomeDynamicListComponent progressForDaysAdl = mock(AwesomeDynamicListComponent.class); stubViewComponent("progressForDays", progressForDaysAdl); given(progressForDaysAdl.getFormComponents()).willReturn(Lists.newArrayList(firstPfdForm, secondPfdForm)); productionPerShiftDetailsHooks.disableComponents(progressForDaysAdl, ProgressType.PLANNED, OrderState.PENDING); verify(progressForDaysAdl).setEnabled(true); verify(firstPfdFirstDailyForm).setFormEnabled(true); verify(firstPfdSecondDailyForm).setFormEnabled(false); verify(firstPfdDailyAdl).setEnabled(true); verify(firstPfdForm).setFormEnabled(true); verify(secondPfdFirstDailyForm).setFormEnabled(true); verify(secondPfdDailyAdl).setEnabled(true); verify(secondPfdForm).setFormEnabled(true); } |
### Question:
PPSHelper { public Long getPpsIdForOrder(final Long orderId) { DataDefinition ppsDateDef = getProductionPerShiftDD(); String query = "select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId"; Entity projectionResults = ppsDateDef.find(query).setLong("orderId", orderId).setMaxResults(1).uniqueResult(); if (projectionResults == null) { return null; } return (Long) projectionResults.getField("ppsId"); } Long getPpsIdForOrder(final Long orderId); Long createPpsForOrderAndReturnId(final Long orderId); Entity createDailyProgressWithShift(final Entity shiftEntity); }### Answer:
@Test public final void shouldGetPpsForOrderReturnExistingPpsId() { Long givenOrderId = 1L; Long expectedPpsId = 50L; given( dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PRODUCTION_PER_SHIFT)).willReturn(dataDefinition); SearchQueryBuilder searchCriteriaBuilder = mock(SearchQueryBuilder.class); given(dataDefinition.find("select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId")) .willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(Mockito.anyInt())).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setLong(Mockito.anyString(), Mockito.eq(givenOrderId))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(entity); given(entity.getField("ppsId")).willReturn(expectedPpsId); final Long resultPpsId = ppsHelper.getPpsIdForOrder(givenOrderId); Assert.assertEquals(expectedPpsId, resultPpsId); }
@Test public final void shouldGetPpsForOrderReturnNullIfPpsDoesNotExists() { Long givenOrderId = 1L; given( dataDefinitionService.get(ProductionPerShiftConstants.PLUGIN_IDENTIFIER, ProductionPerShiftConstants.MODEL_PRODUCTION_PER_SHIFT)).willReturn(dataDefinition); SearchQueryBuilder searchCriteriaBuilder = mock(SearchQueryBuilder.class); given(dataDefinition.find("select id as ppsId from #productionPerShift_productionPerShift where order.id = :orderId")) .willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(Mockito.anyInt())).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.setLong(Mockito.anyString(), Mockito.eq(givenOrderId))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(null); final Long resultPpsId = ppsHelper.getPpsIdForOrder(givenOrderId); Assert.assertNull(resultPpsId); } |
### Question:
OrderRealizationDaysResolver { public LazyStream<OrderRealizationDay> asStreamFrom(final DateTime orderStartDateTime, final List<Shift> shifts) { OrderRealizationDay firstDay = find(orderStartDateTime, 1, true, shifts); return LazyStream.create(firstDay, prevElement -> find(orderStartDateTime, prevElement.getRealizationDayNumber() + 1, false, shifts)); } LazyStream<OrderRealizationDay> asStreamFrom(final DateTime orderStartDateTime, final List<Shift> shifts); OrderRealizationDay find(final DateTime orderStartDateTime, final int startingFrom, final boolean isFirstDay,
final List<Shift> shifts); }### Answer:
@Test public final void shouldProduceStreamWithCorrectFirstDayDate() { DateTime startDate = new DateTime(2014, 12, 4, 23, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); LazyStream<OrderRealizationDay> stream = orderRealizationDaysResolver.asStreamFrom(startDate, shifts); Optional<OrderRealizationDay> firstRealizationDay = FluentIterable.from(stream).limit(1).first(); assertTrue(firstRealizationDay.isPresent()); assertRealizationDayState(firstRealizationDay.get(), 1, startDate.toLocalDate(), ImmutableList.of(shift1)); }
@Test public final void shouldProduceStreamOfRealizationDays1() { DateTime startDate = new DateTime(2014, 8, 14, 3, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); LazyStream<OrderRealizationDay> stream = orderRealizationDaysResolver.asStreamFrom(startDate, shifts); OrderRealizationDay[] streamVals = FluentIterable.from(stream).limit(5).toArray(OrderRealizationDay.class); assertRealizationDayState(streamVals[0], 0, startDate.toLocalDate().minusDays(1), ImmutableList.of(shift1)); assertRealizationDayState(streamVals[1], 1, startDate.toLocalDate(), shifts); assertRealizationDayState(streamVals[2], 2, startDate.toLocalDate().plusDays(1), shifts); assertRealizationDayState(streamVals[3], 5, startDate.toLocalDate().plusDays(4), shifts); assertRealizationDayState(streamVals[4], 6, startDate.toLocalDate().plusDays(5), shifts); }
@Test public final void shouldProduceStreamOfRealizationDays2() { DateTime startDate = new DateTime(2014, 8, 14, 14, 0, 0); List<Shift> shifts = ImmutableList.of(shift1, shift2, shift3); LazyStream<OrderRealizationDay> stream = orderRealizationDaysResolver.asStreamFrom(startDate, shifts); OrderRealizationDay[] streamVals = FluentIterable.from(stream).limit(5).toArray(OrderRealizationDay.class); assertRealizationDayState(streamVals[0], 1, startDate.toLocalDate(), shifts); assertRealizationDayState(streamVals[1], 2, startDate.toLocalDate().plusDays(1), shifts); assertRealizationDayState(streamVals[2], 5, startDate.toLocalDate().plusDays(4), shifts); assertRealizationDayState(streamVals[3], 6, startDate.toLocalDate().plusDays(5), shifts); assertRealizationDayState(streamVals[4], 7, startDate.toLocalDate().plusDays(6), shifts); } |
### Question:
DeliveriesColumnLoaderTSFD { public void addColumnsForDeliveriesTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForDeliveries(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }### Answer:
@Test public void shouldAddColumnsForDeliveriesTSFD() { deliveriesColumnLoaderTSFD.addColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderService).fillColumnsForDeliveries(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoaderTSFD { public void deleteColumnsForDeliveriesTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForDeliveries(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }### Answer:
@Test public void shouldDeleteTSFDcolumnsForDeliveries() { deliveriesColumnLoaderTSFD.deleteColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderService).clearColumnsForDeliveries(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoaderTSFD { public void addColumnsForOrdersTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForOrders(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }### Answer:
@Test public void shouldAddColumnsForOrdersTSFD() { deliveriesColumnLoaderTSFD.addColumnsForOrdersTSFD(); verify(deliveriesColumnLoaderService).fillColumnsForOrders(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoaderTSFD { public void deleteColumnsForOrdersTSFD() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForOrders(TechSubcontrForDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesTSFD(); void deleteColumnsForDeliveriesTSFD(); void addColumnsForOrdersTSFD(); void deleteColumnsForOrdersTSFD(); }### Answer:
@Test public void shouldDeleteColumnsForOrdersTSFD() { deliveriesColumnLoaderTSFD.deleteColumnsForOrdersTSFD(); verify(deliveriesColumnLoaderService).clearColumnsForOrders(Mockito.anyString()); } |
### Question:
TechSubcontrForDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantEnable() { deliveriesColumnLoaderTSFD.addColumnsForDeliveriesTSFD(); deliveriesColumnLoaderTSFD.addColumnsForOrdersTSFD(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }### Answer:
@Test public void shouldMultiTenantEnable() { techSubcontrForDeliveriesOnStartupService.multiTenantEnable(); verify(deliveriesColumnLoaderTSFD).addColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderTSFD).addColumnsForOrdersTSFD(); } |
### Question:
TechSubcontrForDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantDisable() { deliveriesColumnLoaderTSFD.deleteColumnsForDeliveriesTSFD(); deliveriesColumnLoaderTSFD.deleteColumnsForOrdersTSFD(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }### Answer:
@Test public void shouldMultiTenantDisable() { techSubcontrForDeliveriesOnStartupService.multiTenantDisable(); verify(deliveriesColumnLoaderTSFD).deleteColumnsForDeliveriesTSFD(); verify(deliveriesColumnLoaderTSFD).deleteColumnsForOrdersTSFD(); } |
### Question:
CostCalculationValidators { public boolean checkIfTheTechnologyHasCorrectState(final DataDefinition costCalculationDD, final Entity costCalculation) { Entity technology = costCalculation.getBelongsToField(CostCalculationFields.TECHNOLOGY); String state = technology.getStringField(TechnologyFields.STATE); if (TechnologyState.DRAFT.getStringValue().equals(state) || TechnologyState.DECLINED.getStringValue().equals(state)) { costCalculation.addError(costCalculationDD.getField(CostCalculationFields.TECHNOLOGY), "costNormsForOperation.messages.fail.incorrectState"); return false; } return true; } boolean checkIfTheTechnologyHasCorrectState(final DataDefinition costCalculationDD, final Entity costCalculation); boolean checkIfCurrentGlobalIsSelected(final DataDefinition costCalculationDD, final Entity costCalculation); boolean ifSourceOfMaterialIsFromOrderThenOrderIsNeeded(final DataDefinition costCalculationDD,
final Entity costCalculation); }### Answer:
@Test public void shouldTechnologyHasIncorrectState() { given(costCalculation.getBelongsToField(CostCalculationFields.TECHNOLOGY)).willReturn(technology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyStateStringValues.DRAFT); boolean result = costCalculationValidators.checkIfTheTechnologyHasCorrectState(costCalculationDD, costCalculation); assertFalse(result); }
@Test public void shouldTechnologyHasCorrectState() { given(costCalculation.getBelongsToField(CostCalculationFields.TECHNOLOGY)).willReturn(technology); given(technology.getStringField(TechnologyFields.STATE)).willReturn(TechnologyStateStringValues.CHECKED); boolean result = costCalculationValidators.checkIfTheTechnologyHasCorrectState(costCalculationDD, costCalculation); assertTrue(result); } |
### Question:
CostCalculationValidators { public boolean checkIfCurrentGlobalIsSelected(final DataDefinition costCalculationDD, final Entity costCalculation) { String sourceOfMaterialCosts = costCalculation.getStringField(CostCalculationFields.SOURCE_OF_MATERIAL_COSTS); String calculateMaterialCostsMode = costCalculation.getStringField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE); if (SourceOfMaterialCosts.CURRENT_GLOBAL_DEFINITIONS_IN_PRODUCT.getStringValue().equals(sourceOfMaterialCosts) && CalculateMaterialCostsMode.COST_FOR_ORDER.getStringValue().equals(calculateMaterialCostsMode)) { costCalculation.addError(costCalculationDD.getField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE), "costCalculation.messages.optionUnavailable"); return false; } return true; } boolean checkIfTheTechnologyHasCorrectState(final DataDefinition costCalculationDD, final Entity costCalculation); boolean checkIfCurrentGlobalIsSelected(final DataDefinition costCalculationDD, final Entity costCalculation); boolean ifSourceOfMaterialIsFromOrderThenOrderIsNeeded(final DataDefinition costCalculationDD,
final Entity costCalculation); }### Answer:
@Test public void shouldReturnFalseWhenCurrencyGlobalIsSelected() throws Exception { given(costCalculation.getStringField(CostCalculationFields.SOURCE_OF_MATERIAL_COSTS)).willReturn( SourceOfMaterialCosts.CURRENT_GLOBAL_DEFINITIONS_IN_PRODUCT.getStringValue()); given(costCalculation.getStringField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE)).willReturn( CalculateMaterialCostsMode.COST_FOR_ORDER.getStringValue()); boolean result = costCalculationValidators.checkIfCurrentGlobalIsSelected(costCalculationDD, costCalculation); assertFalse(result); }
@Test public void shouldReturnTrueWhenCalculateMaterialCostsModeIsNominal() throws Exception { given(costCalculation.getStringField(CostCalculationFields.SOURCE_OF_MATERIAL_COSTS)).willReturn( SourceOfMaterialCosts.CURRENT_GLOBAL_DEFINITIONS_IN_PRODUCT.getStringValue()); given(costCalculation.getStringField(CostCalculationFields.CALCULATE_MATERIAL_COSTS_MODE)).willReturn( CalculateMaterialCostsMode.NOMINAL.getStringValue()); boolean result = costCalculationValidators.checkIfCurrentGlobalIsSelected(costCalculationDD, costCalculation); assertTrue(result); } |
### Question:
StaffDetailsHooks { public void enabledIndividualCost(final ViewDefinitionState view) { FieldComponent individual = (FieldComponent) view.getComponentByReference("determinedIndividual"); FieldComponent individualLaborCost = (FieldComponent) view.getComponentByReference("individualLaborCost"); if (individual.getFieldValue() != null && individual.getFieldValue().equals("1")) { individualLaborCost.setEnabled(true); } else { individualLaborCost.setEnabled(false); } individualLaborCost.requestComponentUpdateState(); } void enabledIndividualCost(final ViewDefinitionState view); void setCurrency(final ViewDefinitionState view); void fillFieldAboutWageGroup(final ViewDefinitionState view); }### Answer:
@Test public void shouldEnabledFieldWhenCheckBoxIsSelected() throws Exception { String result = "1"; when(view.getComponentByReference("determinedIndividual")).thenReturn(field1); when(view.getComponentByReference("individualLaborCost")).thenReturn(field2); when(field1.getFieldValue()).thenReturn(result); detailsHooks.enabledIndividualCost(view); Mockito.verify(field2).setEnabled(true); }
@Test public void shouldDisabledFieldWhenCheckBoxIsSelected() throws Exception { String result = "0"; when(view.getComponentByReference("determinedIndividual")).thenReturn(field1); when(view.getComponentByReference("individualLaborCost")).thenReturn(field2); when(field1.getFieldValue()).thenReturn(result); detailsHooks.enabledIndividualCost(view); Mockito.verify(field2).setEnabled(false); } |
### Question:
StaffDetailsHooks { public void setCurrency(final ViewDefinitionState view) { FieldComponent laborHourlyCostUNIT = (FieldComponent) view.getComponentByReference("individualLaborCostCURRENCY"); FieldComponent laborCostFromWageGroupsUNIT = (FieldComponent) view .getComponentByReference("laborCostFromWageGroupsCURRENCY"); laborHourlyCostUNIT.setFieldValue(currencyService.getCurrencyAlphabeticCode()); laborCostFromWageGroupsUNIT.setFieldValue(currencyService.getCurrencyAlphabeticCode()); laborHourlyCostUNIT.requestComponentUpdateState(); laborCostFromWageGroupsUNIT.requestComponentUpdateState(); } void enabledIndividualCost(final ViewDefinitionState view); void setCurrency(final ViewDefinitionState view); void fillFieldAboutWageGroup(final ViewDefinitionState view); }### Answer:
@Test public void shouldFillFieldCurrency() throws Exception { String currency = "PLN"; when(view.getComponentByReference("individualLaborCostCURRENCY")).thenReturn(field1); when(view.getComponentByReference("laborCostFromWageGroupsCURRENCY")).thenReturn(field2); when(currencyService.getCurrencyAlphabeticCode()).thenReturn(currency); detailsHooks.setCurrency(view); Mockito.verify(field1).setFieldValue(currency); Mockito.verify(field2).setFieldValue(currency); } |
### Question:
StaffDetailsHooks { public void fillFieldAboutWageGroup(final ViewDefinitionState view) { LookupComponent lookup = (LookupComponent) view.getComponentByReference("wageGroup"); Entity wageGroup = lookup.getEntity(); FieldComponent laborCostFromWageGroups = (FieldComponent) view.getComponentByReference("laborCostFromWageGroups"); FieldComponent superiorWageGroups = (FieldComponent) view.getComponentByReference("superiorWageGroups"); if (wageGroup != null) { laborCostFromWageGroups.setFieldValue(wageGroup.getField(LABOR_HOURLY_COST)); superiorWageGroups.setFieldValue(wageGroup.getStringField(SUPERIOR_WAGE_GROUP)); } else { laborCostFromWageGroups.setFieldValue(null); superiorWageGroups.setFieldValue(null); } } void enabledIndividualCost(final ViewDefinitionState view); void setCurrency(final ViewDefinitionState view); void fillFieldAboutWageGroup(final ViewDefinitionState view); }### Answer:
@Test public void shouldFillFieldValuesOfSelectedWageGroup() throws Exception { String superiorWageGroup = "1234"; when(view.getComponentByReference("wageGroup")).thenReturn(lookup); when(lookup.getEntity()).thenReturn(wageGroup); when(view.getComponentByReference("laborCostFromWageGroups")).thenReturn(field1); when(view.getComponentByReference("superiorWageGroups")).thenReturn(field2); when(wageGroup.getField(LABOR_HOURLY_COST)).thenReturn(BigDecimal.ONE); when(wageGroup.getStringField(SUPERIOR_WAGE_GROUP)).thenReturn(superiorWageGroup); detailsHooks.fillFieldAboutWageGroup(view); Mockito.verify(field1).setFieldValue(BigDecimal.ONE); Mockito.verify(field2).setFieldValue(superiorWageGroup); } |
### Question:
WageGroupsDetailsHooks { public void setCurrency(final ViewDefinitionState view) { FieldComponent individualLaborCostUNIT = (FieldComponent) view .getComponentByReference(WageGroupFields.LABOR_HOURLY_COST_CURRENCY); individualLaborCostUNIT.setFieldValue(currencyService.getCurrencyAlphabeticCode()); individualLaborCostUNIT.requestComponentUpdateState(); } void setCurrency(final ViewDefinitionState view); }### Answer:
@Test public void shouldFillFieldWithCurrency() throws Exception { String currency = "pln"; when(view.getComponentByReference("laborHourlyCostCURRENCY")).thenReturn(field); when(currencyService.getCurrencyAlphabeticCode()).thenReturn(currency); hooks.setCurrency(view); Mockito.verify(field).setFieldValue(currency); } |
### Question:
StaffHooks { public void saveLaborHourlyCost(final DataDefinition dataDefinition, final Entity entity) { boolean individual = entity.getBooleanField(DETERMINED_INDIVIDUAL); if (individual) { entity.setField("laborHourlyCost", entity.getField(INDIVIDUAL_LABOR_COST)); } else { Entity wageGroup = entity.getBelongsToField(WAGE_GROUP); if (wageGroup == null) { entity.setField("laborHourlyCost", null); return; } entity.setField("laborHourlyCost", wageGroup.getField(LABOR_HOURLY_COST)); } } void saveLaborHourlyCost(final DataDefinition dataDefinition, final Entity entity); }### Answer:
@Test public void shouldSaveIndividualCost() throws Exception { when(entity.getBooleanField(DETERMINED_INDIVIDUAL)).thenReturn(true); when(entity.getField(INDIVIDUAL_LABOR_COST)).thenReturn(BigDecimal.ONE); hooks.saveLaborHourlyCost(dataDefinition, entity); Mockito.verify(entity).setField("laborHourlyCost", BigDecimal.ONE); }
@Test public void shouldReturnWhenWageDoesnotExists() throws Exception { when(entity.getBooleanField(DETERMINED_INDIVIDUAL)).thenReturn(false); when(entity.getBelongsToField(WAGE_GROUP)).thenReturn(null); hooks.saveLaborHourlyCost(dataDefinition, entity); Mockito.verify(entity).setField("laborHourlyCost", null); }
@Test public void shouldSaveCostFromWageGroup() throws Exception { when(entity.getBooleanField(DETERMINED_INDIVIDUAL)).thenReturn(false); when(entity.getBelongsToField(WAGE_GROUP)).thenReturn(wageGroup); when(wageGroup.getField(LABOR_HOURLY_COST)).thenReturn(BigDecimal.TEN); hooks.saveLaborHourlyCost(dataDefinition, entity); Mockito.verify(entity).setField("laborHourlyCost", BigDecimal.TEN); } |
### Question:
DeliveriesColumnLoaderCNID { public void addColumnsForDeliveriesCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForDeliveries(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }### Answer:
@Test public void shouldAddColumnsForDeliveriesCNID() { deliveriesColumnLoaderCNID.addColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderService).fillColumnsForDeliveries(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoaderCNID { public void deleteColumnsForDeliveriesCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForDeliveries(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }### Answer:
@Test public void shouldDeleteColumnsForDeliveriesCNID() { deliveriesColumnLoaderCNID.deleteColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderService).clearColumnsForDeliveries(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoaderCNID { public void addColumnsForOrdersCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForOrders(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }### Answer:
@Test public void shouldAddColumnsForOrdersCNID() { deliveriesColumnLoaderCNID.addColumnsForOrdersCNID(); verify(deliveriesColumnLoaderService).fillColumnsForOrders(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoaderCNID { public void deleteColumnsForOrdersCNID() { if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForOrders(CatNumbersInDeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveriesCNID(); void deleteColumnsForDeliveriesCNID(); void addColumnsForOrdersCNID(); void deleteColumnsForOrdersCNID(); }### Answer:
@Test public void shouldDeleteColumnsForOrdersCNID() { deliveriesColumnLoaderCNID.deleteColumnsForOrdersCNID(); verify(deliveriesColumnLoaderService).clearColumnsForOrders(Mockito.anyString()); } |
### Question:
OrderedProductHooksCNID { public void updateOrderedProductCatalogNumber(final DataDefinition orderedProductDD, final Entity orderedProduct) { catNumbersInDeliveriesService.updateProductCatalogNumber(orderedProduct); } void updateOrderedProductCatalogNumber(final DataDefinition orderedProductDD, final Entity orderedProduct); }### Answer:
@Test public void shouldUpdateOrderedProductCatalogNumber() { orderedProductHooksCNID.updateOrderedProductCatalogNumber(orderedProductDD, orderedProduct); verify(catNumbersInDeliveriesService).updateProductCatalogNumber(orderedProduct); } |
### Question:
DeliveredProductHooksCNID { public void updateDeliveredProductCatalogNumber(final DataDefinition deliveredProductDD, final Entity deliveredProduct) { catNumbersInDeliveriesService.updateProductCatalogNumber(deliveredProduct); } void updateDeliveredProductCatalogNumber(final DataDefinition deliveredProductDD, final Entity deliveredProduct); }### Answer:
@Test public void shouldUpdateDeliveredProductCatalogNumber() { deliveredProductHooksCNID.updateDeliveredProductCatalogNumber(deliveredProductDD, deliveredProduct); verify(catNumbersInDeliveriesService).updateProductCatalogNumber(deliveredProduct); } |
### Question:
DeliveryHooksCNID { public void updateOrderedProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery) { catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); } void updateOrderedProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); void updateDeliveredProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); }### Answer:
@Test public void shouldUpdateOrderedProductsCatalogNumbers() { deliveryHooksCNID.updateOrderedProductsCatalogNumbers(deliveryDD, delivery); verify(catNumbersInDeliveriesService).updateProductsCatalogNumbers(delivery, ORDERED_PRODUCTS); } |
### Question:
DeliveryHooksCNID { public void updateDeliveredProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery) { catNumbersInDeliveriesService.updateProductsCatalogNumbers(delivery, DELIVERED_PRODUCTS); } void updateOrderedProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); void updateDeliveredProductsCatalogNumbers(final DataDefinition deliveryDD, final Entity delivery); }### Answer:
@Test public void shouldUpdateDeliveredProductsCatalogNumbers() { deliveryHooksCNID.updateDeliveredProductsCatalogNumbers(deliveryDD, delivery); verify(catNumbersInDeliveriesService).updateProductsCatalogNumbers(delivery, DELIVERED_PRODUCTS); } |
### Question:
CatNumbersInDeliveriesServiceImpl implements CatNumbersInDeliveriesService { @Override public void updateProductCatalogNumber(final Entity deliveryProduct) { Entity delivery = deliveryProduct.getBelongsToField(DELIVERY); Entity supplier = delivery.getBelongsToField(SUPPLIER); Entity product = deliveryProduct.getBelongsToField(PRODUCT); Entity productCatalogNumber = productCatalogNumbersService.getProductCatalogNumber(product, supplier); if (productCatalogNumber != null) { deliveryProduct.setField(PRODUCT_CATALOG_NUMBER, productCatalogNumber); } } @Override void updateProductCatalogNumber(final Entity deliveryProduct); @Override void updateProductsCatalogNumbers(final Entity delivery, final String productsName); }### Answer:
@Test public void shouldntUpdateProductCatalogNumberIfEntityIsntSaved() { given(deliveryProduct.getBelongsToField(DELIVERY)).willReturn(delivery); given(delivery.getBelongsToField(SUPPLIER)).willReturn(supplier); given(deliveryProduct.getBelongsToField(PRODUCT)).willReturn(product); given(productCatalogNumbersService.getProductCatalogNumber(product, supplier)).willReturn(null); catNumbersInDeliveriesService.updateProductCatalogNumber(deliveryProduct); verify(deliveryProduct, never()).setField(Mockito.anyString(), Mockito.any(Entity.class)); }
@Test public void shouldUpdateProductCatalogNumberIfEntityIsntSaved() { given(deliveryProduct.getBelongsToField(DELIVERY)).willReturn(delivery); given(delivery.getBelongsToField(SUPPLIER)).willReturn(supplier); given(deliveryProduct.getBelongsToField(PRODUCT)).willReturn(product); given(productCatalogNumbersService.getProductCatalogNumber(product, supplier)).willReturn(productCatalogNumber); catNumbersInDeliveriesService.updateProductCatalogNumber(deliveryProduct); verify(deliveryProduct).setField(Mockito.anyString(), Mockito.any(Entity.class)); } |
### Question:
CatNumbersInDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantEnable() { deliveriesColumnLoaderCNID.addColumnsForDeliveriesCNID(); deliveriesColumnLoaderCNID.addColumnsForOrdersCNID(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }### Answer:
@Test public void shouldMultiTenantEnable() { catNumbersInDeliveriesOnStartupService.multiTenantEnable(); verify(deliveriesColumnLoaderCNID).addColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderCNID).addColumnsForOrdersCNID(); } |
### Question:
CatNumbersInDeliveriesOnStartupService extends Module { @Transactional @Override public void multiTenantDisable() { deliveriesColumnLoaderCNID.deleteColumnsForDeliveriesCNID(); deliveriesColumnLoaderCNID.deleteColumnsForOrdersCNID(); } @Transactional @Override void multiTenantEnable(); @Transactional @Override void multiTenantDisable(); }### Answer:
@Test public void shouldMultiTenantDisable() { catNumbersInDeliveriesOnStartupService.multiTenantDisable(); verify(deliveriesColumnLoaderCNID).deleteColumnsForDeliveriesCNID(); verify(deliveriesColumnLoaderCNID).deleteColumnsForOrdersCNID(); } |
### Question:
ProductDetailsListenersO { public final void showOrdersWithProductMain(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } String productNumber = product.getStringField(NUMBER); if (productNumber == null) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("productNumber", applyInOperator(productNumber)); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrders"); String url = "../page/orders/ordersList.html"; view.redirectTo(url, false, true, parameters); } final void showOrdersWithProductMain(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showOrdersWithProductPlanned(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); }### Answer:
@Test public void shouldntShowOrdersWithProductMainIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/orders/ordersList.html"; productDetailsListenersO.showOrdersWithProductMain(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldntShowOrdersWithProductMainIfProductIsSavedAndProductNumberIsNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(null); String url = "../page/orders/ordersList.html"; productDetailsListenersO.showOrdersWithProductMain(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldShowOrdersWithProductMainIfProductIsSavedAndProductNumberIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(L_PRODUCT_NUMBER); filters.put("productNumber", "[" + L_PRODUCT_NUMBER + "]"); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrders"); String url = "../page/orders/ordersList.html"; productDetailsListenersO.showOrdersWithProductMain(view, null, null); verify(view).redirectTo(url, false, true, parameters); } |
### Question:
TransferModelHooks { public void copyProductionOrConsumptionDataFromBelongingTransformation(final DataDefinition dd, final Entity transfer) { Entity transformations = transfer.getBelongsToField(TRANSFORMATIONS_PRODUCTION); if (transformations == null) { transformations = transfer.getBelongsToField(TRANSFORMATIONS_CONSUMPTION); if (transformations == null) { return; } else { transfer.setField(TYPE, CONSUMPTION.getStringValue()); transfer.setField(LOCATION_FROM, transformations.getBelongsToField(LOCATION_FROM)); } } else { transfer.setField(TYPE, PRODUCTION.getStringValue()); transfer.setField(LOCATION_TO, transformations.getBelongsToField(LOCATION_TO)); } transfer.setField(TIME, transformations.getField(TIME)); transfer.setField(STAFF, transformations.getBelongsToField(STAFF)); } void copyProductionOrConsumptionDataFromBelongingTransformation(final DataDefinition dd, final Entity transfer); }### Answer:
@Test public void shouldCopyProductionDataFromBelongingTransformation() { given(transfer.getBelongsToField(TRANSFORMATIONS_PRODUCTION)).willReturn(transformation); given(transformation.getField(TIME)).willReturn("1234"); given(transformation.getBelongsToField(LOCATION_FROM)).willReturn(locationFrom); given(transformation.getBelongsToField(LOCATION_TO)).willReturn(locationTo); given(transformation.getBelongsToField(STAFF)).willReturn(staff); materialFlowTransferModelHooks.copyProductionOrConsumptionDataFromBelongingTransformation(transferDD, transfer); verify(transfer).setField(TYPE, PRODUCTION.getStringValue()); verify(transfer).setField(TIME, "1234"); verify(transfer).setField(LOCATION_TO, locationTo); verify(transfer).setField(STAFF, staff); }
@Test public void shouldCopyConsumptionDataFromBelongingTransformation() { given(transfer.getBelongsToField(TRANSFORMATIONS_CONSUMPTION)).willReturn(transformation); given(transformation.getField(TIME)).willReturn("1234"); given(transformation.getBelongsToField(LOCATION_TO)).willReturn(locationTo); given(transformation.getBelongsToField(LOCATION_FROM)).willReturn(locationFrom); given(transformation.getBelongsToField(STAFF)).willReturn(staff); materialFlowTransferModelHooks.copyProductionOrConsumptionDataFromBelongingTransformation(transferDD, transfer); verify(transfer).setField(TYPE, CONSUMPTION.getStringValue()); verify(transfer).setField(TIME, "1234"); verify(transfer).setField(LOCATION_FROM, locationFrom); verify(transfer).setField(STAFF, staff); }
@Test public void shouldNotTriggerCopyingWhenSavingPlainTransfer() { materialFlowTransferModelHooks.copyProductionOrConsumptionDataFromBelongingTransformation(transferDD, transfer); verify(transfer, never()).setField(anyString(), any()); } |
### Question:
ProductDetailsListenersO { public final void showOrdersWithProductPlanned(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } String productNumber = product.getStringField(NUMBER); if (productNumber == null) { return; } Map<String, String> filters = Maps.newHashMap(); filters.put("productNumber", applyInOperator(productNumber)); Map<String, Object> gridOptions = Maps.newHashMap(); gridOptions.put(L_FILTERS, filters); Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrdersPlanning"); String url = "../page/orders/ordersPlanningList.html"; view.redirectTo(url, false, true, parameters); } final void showOrdersWithProductMain(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); final void showOrdersWithProductPlanned(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); }### Answer:
@Test public void shouldntShowOrdersWithProductPlannedIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/orders/ordersPlanningList.html"; productDetailsListenersO.showOrdersWithProductPlanned(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldntShowOrdersWithProductPlannedIfProductIsSavedAndProductNumberIsNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(null); String url = "../page/orders/ordersPlanningList.html"; productDetailsListenersO.showOrdersWithProductPlanned(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); }
@Test public void shouldShowOrdersWithProductPlannedIfProductIsSavedAndProductNumberIsntNull() { given(product.getId()).willReturn(L_ID); given(product.getStringField(NUMBER)).willReturn(L_PRODUCT_NUMBER); filters.put("productNumber", "[" + L_PRODUCT_NUMBER + "]"); gridOptions.put(L_FILTERS, filters); parameters.put(L_GRID_OPTIONS, gridOptions); parameters.put(L_WINDOW_ACTIVE_MENU, "orders.productionOrdersPlanning"); String url = "../page/orders/ordersPlanningList.html"; productDetailsListenersO.showOrdersWithProductPlanned(view, null, null); verify(view).redirectTo(url, false, true, parameters); } |
### Question:
ParametersListenersO { public void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { Long parameterId = (Long) componentState.getFieldValue(); if (parameterId != null) { String url = "../page/orders/ordersParameters.html?context={\"form.id\":\"" + parameterId + "\"}"; view.redirectTo(url, false, true); } } void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState,
final ComponentState componentState, final String[] args); void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }### Answer:
@Test public void shouldRedirectToOrdersParametersIfParameterIdIsntNull() { Long parameterId = 1L; given(componentState.getFieldValue()).willReturn(parameterId); String url = "../page/orders/ordersParameters.html?context={\"form.id\":\"" + parameterId + "\"}"; parametersListenersO.redirectToOrdersParameters(view, componentState, null); verify(view).redirectTo(url, false, true); }
@Test public void shouldntRedirectToOrdersParametersIfParameterIdIsNull() { Long parameterId = null; given(componentState.getFieldValue()).willReturn(parameterId); String url = "../page/orders/ordersParameters.html?context={\"form.id\":\"" + parameterId + "\"}"; parametersListenersO.redirectToOrdersParameters(view, componentState, null); verify(view, never()).redirectTo(url, false, true); } |
### Question:
ParametersListenersO { public void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState, final ComponentState componentState, final String[] args) { Long dictionaryId = getDictionaryId("reasonTypeOfChangingOrderState"); if (dictionaryId != null) { String url = "../page/smartDictionaries/dictionaryDetails.html?context={\"form.id\":\"" + dictionaryId + "\"}"; viewDefinitionState.redirectTo(url, false, true); } } void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState,
final ComponentState componentState, final String[] args); void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }### Answer:
@Test public void shouldRedirectToDeviationsDictionaryIfDictionaryIdIsntNull() { Long dictionaryId = 1L; given(dataDefinitionService.get("smartModel", "dictionary")).willReturn(dictionaryDD); given(dictionaryDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(SearchRestrictions.eq("name", "reasonTypeOfChangingOrderState"))).willReturn( searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(1)).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(dictionary); given(dictionary.getId()).willReturn(dictionaryId); String url = "../page/smartDictionaries/dictionaryDetails.html?context={\"form.id\":\"" + dictionaryId + "\"}"; parametersListenersO.redirectToDeviationsDictionary(view, componentState, null); verify(view).redirectTo(url, false, true); }
@Test public void shouldntRedirectToDeviationsDictionaryfDictionaryIdIsnull() { Long dictionaryId = null; given(dataDefinitionService.get("smartModel", "dictionary")).willReturn(dictionaryDD); given(dictionaryDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(SearchRestrictions.eq("name", "reasonTypeOfChangingOrderState"))).willReturn( searchCriteriaBuilder); given(searchCriteriaBuilder.setMaxResults(1)).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.uniqueResult()).willReturn(null); String url = "../page/smartDictionaries/dictionaryDetails.html?context={\"form.id\":\"" + dictionaryId + "\"}"; parametersListenersO.redirectToDeviationsDictionary(view, componentState, null); verify(view, never()).redirectTo(url, false, true); } |
### Question:
ParametersListenersO { public void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { String componentStateName = componentState.getName(); if (REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); } else if (REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); } else if (REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); } else if (REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO.equals(componentStateName)) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); } } void redirectToOrdersParameters(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); void redirectToDeviationsDictionary(final ViewDefinitionState viewDefinitionState,
final ComponentState componentState, final String[] args); void showTimeField(final ViewDefinitionState view, final ComponentState componentState, final String[] args); }### Answer:
@Test public void shouldShowTimeFieldForDelayedEffectiveDateFrom() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); }
@Test public void shouldShowTimeFieldForEarlierEffectiveDateFrom() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); }
@Test public void shouldShowTimeFieldForDelayedEffectiveDateTo() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); }
@Test public void shouldShowTimeFieldForEarlierEffectiveDateTo() { given(componentState.getName()).willReturn(REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO); parametersListenersO.showTimeField(view, componentState, null); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); } |
### Question:
ParametersHooksO { public void showTimeFields(final ViewDefinitionState view) { orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); orderService.changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); orderService.changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); } void showTimeFields(final ViewDefinitionState view); void hideTabs(final ViewDefinitionState view); }### Answer:
@Test public void shouldShowTimeFields() { parametersHooksO.showTimeFields(view); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM, DELAYED_EFFECTIVE_DATE_FROM_TIME); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM, EARLIER_EFFECTIVE_DATE_FROM_TIME); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO, DELAYED_EFFECTIVE_DATE_TO_TIME); verify(orderService).changeFieldState(view, REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO, EARLIER_EFFECTIVE_DATE_TO_TIME); } |
### Question:
ProductDetailsViewHooksO { public void updateRibbonState(final ViewDefinitionState view) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonGroup orders = (RibbonGroup) window.getRibbon().getGroupByName("orders"); RibbonActionItem showOrdersWithProductMain = (RibbonActionItem) orders.getItemByName("showOrdersWithProductMain"); RibbonActionItem showOrdersWithProductPlanned = (RibbonActionItem) orders.getItemByName("showOrdersWithProductPlanned"); if (product.getId() != null) { updateButtonState(showOrdersWithProductMain, true); updateButtonState(showOrdersWithProductPlanned, true); return; } updateButtonState(showOrdersWithProductMain, false); updateButtonState(showOrdersWithProductPlanned, false); } void updateRibbonState(final ViewDefinitionState view); }### Answer:
@Test public void shouldntUpdateRibbonStateIfProductIsntSaved() { given(product.getId()).willReturn(null); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("orders")).willReturn(orders); given(orders.getItemByName("showOrdersWithProductMain")).willReturn(showOrdersWithProductMain); given(orders.getItemByName("showOrdersWithProductPlanned")).willReturn(showOrdersWithProductPlanned); productDetailsViewHooksO.updateRibbonState(view); verify(showOrdersWithProductMain).setEnabled(false); verify(showOrdersWithProductPlanned).setEnabled(false); }
@Test public void shouldUpdateRibbonStateIfProductIsSaved() { given(product.getId()).willReturn(L_ID); given(product.getBelongsToField("technologyGroup")).willReturn(technologyGroup); given(view.getComponentByReference("window")).willReturn((ComponentState) window); given(window.getRibbon()).willReturn(ribbon); given(ribbon.getGroupByName("orders")).willReturn(orders); given(orders.getItemByName("showOrdersWithProductMain")).willReturn(showOrdersWithProductMain); given(orders.getItemByName("showOrdersWithProductPlanned")).willReturn(showOrdersWithProductPlanned); productDetailsViewHooksO.updateRibbonState(view); verify(showOrdersWithProductMain).setEnabled(true); verify(showOrdersWithProductPlanned).setEnabled(true); } |
### Question:
CommonReasonTypeModelHooks { public void updateDate(final Entity reasonTypeEntity, final DeviationModelDescriber deviationModelDescriber) { if (reasonHasNotBeenSavedYet(reasonTypeEntity) || reasonHasChanged(reasonTypeEntity, deviationModelDescriber)) { reasonTypeEntity.setField(CommonReasonTypeFields.DATE, new Date()); } } void updateDate(final Entity reasonTypeEntity, final DeviationModelDescriber deviationModelDescriber); }### Answer:
@Test public final void shouldSetCurrentDateOnUpdate() { Date dateBefore = new Date(); stubReasonEntityId(1L); stubFindResults(false); commonReasonTypeModelHooks.updateDate(reasonTypeEntity, deviationModelDescriber); verify(reasonTypeEntity).setField(eq(CommonReasonTypeFields.DATE), dateCaptor.capture()); Date capturedDate = dateCaptor.getValue(); Date dateAfter = new Date(); Assert.assertTrue(capturedDate.compareTo(dateBefore) >= 0 && capturedDate.compareTo(dateAfter) <= 0); }
@Test public final void shouldSetCurrentDateOnCreate() { Date dateBefore = new Date(); stubReasonEntityId(null); stubFindResults(false); commonReasonTypeModelHooks.updateDate(reasonTypeEntity, deviationModelDescriber); verify(reasonTypeEntity).setField(eq(CommonReasonTypeFields.DATE), dateCaptor.capture()); Date capturedDate = dateCaptor.getValue(); Date dateAfter = new Date(); Assert.assertTrue(capturedDate.compareTo(dateBefore) >= 0 && capturedDate.compareTo(dateAfter) <= 0); }
@Test public final void shouldNotSetCurrentDateIfTypeFieldValueDidNotChange() { stubReasonEntityId(1L); stubFindResults(true); commonReasonTypeModelHooks.updateDate(reasonTypeEntity, deviationModelDescriber); verify(reasonTypeEntity, never()).setField(eq(CommonReasonTypeFields.DATE), any()); } |
### Question:
LineChangeoverNormsHooks { public boolean checkRequiredField(final DataDefinition changeoverNormDD, final Entity changeoverNorm) { String changeoverType = changeoverNorm.getStringField(LineChangeoverNormsFields.CHANGEOVER_TYPE); if (changeoverType.equals(ChangeoverType.FOR_TECHNOLOGY.getStringValue())) { for (String reference : Arrays.asList(FROM_TECHNOLOGY, TO_TECHNOLOGY)) { if (changeoverNorm.getBelongsToField(reference) == null) { changeoverNorm.addError(changeoverNorm.getDataDefinition().getField(reference), L_LINE_CHANGEOVER_NORMS_LINE_CHANGEOVER_NORM_FIELD_IS_REQUIRED); return false; } } } else { for (String reference : Arrays.asList(FROM_TECHNOLOGY_GROUP, TO_TECHNOLOGY_GROUP)) { if (changeoverNorm.getBelongsToField(reference) == null) { changeoverNorm.addError(changeoverNorm.getDataDefinition().getField(reference), L_LINE_CHANGEOVER_NORMS_LINE_CHANGEOVER_NORM_FIELD_IS_REQUIRED); return false; } } } return true; } boolean checkUniqueNorms(final DataDefinition changeoverNormDD, final Entity changeoverNorm); boolean checkRequiredField(final DataDefinition changeoverNormDD, final Entity changeoverNorm); }### Answer:
@Test public void shouldReturnErrorWhenRequiredFieldForTechnologyIsNotFill() { given(changeoverNorm.getStringField(LineChangeoverNormsFields.CHANGEOVER_TYPE)).willReturn("01forTechnology"); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY)).willReturn(null); given(changeoverNorm.getDataDefinition()).willReturn(changeoverNormDD); given(changeoverNormDD.getField(FROM_TECHNOLOGY)).willReturn(field); boolean result = hooks.checkRequiredField(changeoverNormDD, changeoverNorm); Assert.isTrue(!result); verify(changeoverNorm).addError(field, L_ERROR); }
@Test public void shouldReturnErrorWhenRequiredFieldForTechnologyGroupIsNotFill() throws Exception { given(changeoverNorm.getStringField(LineChangeoverNormsFields.CHANGEOVER_TYPE)).willReturn("02forTechnologyGroup"); given(changeoverNorm.getBelongsToField(FROM_TECHNOLOGY_GROUP)).willReturn(fromTechnologyGroup); given(changeoverNorm.getBelongsToField(TO_TECHNOLOGY_GROUP)).willReturn(null); given(changeoverNorm.getDataDefinition()).willReturn(changeoverNormDD); given(changeoverNormDD.getField(TO_TECHNOLOGY_GROUP)).willReturn(field); boolean result = hooks.checkRequiredField(changeoverNormDD, changeoverNorm); Assert.isTrue(!result); verify(changeoverNorm).addError(field, L_ERROR); } |
### Question:
OrderHooks { public boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order) { Entity product = order.getBelongsToField(OrderFields.PRODUCT); if (product == null) { return true; } BigDecimal plannedQuantity = order.getDecimalField(OrderFields.PLANNED_QUANTITY); if (plannedQuantity == null) { order.addError(orderDD.getField(OrderFields.PLANNED_QUANTITY), "orders.validate.global.error.plannedQuantityError"); return false; } else { return true; } } boolean validatesWith(final DataDefinition orderDD, final Entity order); void onCreate(final DataDefinition orderDD, final Entity order); void onSave(final DataDefinition orderDD, final Entity order); void onCopy(final DataDefinition orderDD, final Entity order); void setRemainingQuantity(final Entity order); void onDelete(final DataDefinition orderDD, final Entity order); boolean setDateChanged(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Entity order,
final Object fieldOldValue, final Object fieldNewValue); void setInitialState(final DataDefinition orderDD, final Entity order); boolean checkOrderDates(final DataDefinition orderDD, final Entity order); boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order); void copyStartDate(final DataDefinition orderDD, final Entity order); void copyEndDate(final DataDefinition orderDD, final Entity order); boolean validateDates(final DataDefinition orderDD, final Entity order); void copyProductQuantity(final DataDefinition orderDD, final Entity order); void onCorrectingTheRequestedVolume(final DataDefinition orderDD, final Entity order); boolean neededWhenCorrectingTheRequestedVolume(); void setCommissionedPlannedQuantity(final DataDefinition orderDD, final Entity order); void setProductQuantity(final DataDefinition orderDD, final Entity order); void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order); static final String L_TYPE_OF_PRODUCTION_RECORDING; static final String BACKUP_TECHNOLOGY_PREFIX; static final long SECOND_MILLIS; static final List<String> sourceDateFields; }### Answer:
@Test public void shouldReturnTrueForPlannedQuantityValidationIfThereIsNoProduct() throws Exception { stubBelongsToField(order, OrderFields.PRODUCT, null); boolean result = orderHooks.checkOrderPlannedQuantity(orderDD, order); assertTrue(result); }
@Test public void shouldReturnTrueForPlannedQuantityValidation() throws Exception { stubBelongsToField(order, OrderFields.PRODUCT, product); stubDecimalField(order, OrderFields.PLANNED_QUANTITY, BigDecimal.ONE); boolean result = orderHooks.checkOrderPlannedQuantity(orderDD, order); assertTrue(result); }
@Test public void shouldReturnFalseForPlannedQuantityValidation() throws Exception { stubBelongsToField(order, OrderFields.PRODUCT, product); stubDecimalField(order, OrderFields.PLANNED_QUANTITY, null); given(orderDD.getField(OrderFields.PLANNED_QUANTITY)).willReturn(plannedQuantityField); boolean result = orderHooks.checkOrderPlannedQuantity(orderDD, order); assertFalse(result); verify(order).addError(plannedQuantityField, "orders.validate.global.error.plannedQuantityError"); } |
### Question:
OrderHooks { public void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order) { order.setField(OrderFields.STATE, OrderState.PENDING.getStringValue()); order.setField(OrderFields.EFFECTIVE_DATE_TO, null); order.setField(OrderFields.EFFECTIVE_DATE_FROM, null); order.setField(OrderFields.CORRECTED_DATE_FROM, null); order.setField(OrderFields.CORRECTED_DATE_TO, null); order.setField(OrderFields.DATE_FROM, order.getDateField(OrderFields.START_DATE)); order.setField(OrderFields.DATE_TO, order.getDateField(OrderFields.FINISH_DATE)); order.setField(OrderFields.DONE_QUANTITY, null); order.setField(OrderFields.WASTES_QUANTITY, null); order.setField(OrderFields.EXTERNAL_NUMBER, null); order.setField(OrderFields.EXTERNAL_SYNCHRONIZED, true); order.setField(OrderFields.COMMENT_REASON_TYPE_CORRECTION_DATE_FROM, null); order.setField(OrderFields.COMMENT_REASON_TYPE_CORRECTION_DATE_TO, null); order.setField(OrderFields.COMMENT_REASON_DEVIATION_EFFECTIVE_END, null); order.setField(OrderFields.COMMENT_REASON_DEVIATION_EFFECTIVE_START, null); order.setField(OrderFields.COMMENT_REASON_TYPE_DEVIATIONS_QUANTITY, null); } boolean validatesWith(final DataDefinition orderDD, final Entity order); void onCreate(final DataDefinition orderDD, final Entity order); void onSave(final DataDefinition orderDD, final Entity order); void onCopy(final DataDefinition orderDD, final Entity order); void setRemainingQuantity(final Entity order); void onDelete(final DataDefinition orderDD, final Entity order); boolean setDateChanged(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Entity order,
final Object fieldOldValue, final Object fieldNewValue); void setInitialState(final DataDefinition orderDD, final Entity order); boolean checkOrderDates(final DataDefinition orderDD, final Entity order); boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order); void copyStartDate(final DataDefinition orderDD, final Entity order); void copyEndDate(final DataDefinition orderDD, final Entity order); boolean validateDates(final DataDefinition orderDD, final Entity order); void copyProductQuantity(final DataDefinition orderDD, final Entity order); void onCorrectingTheRequestedVolume(final DataDefinition orderDD, final Entity order); boolean neededWhenCorrectingTheRequestedVolume(); void setCommissionedPlannedQuantity(final DataDefinition orderDD, final Entity order); void setProductQuantity(final DataDefinition orderDD, final Entity order); void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order); static final String L_TYPE_OF_PRODUCTION_RECORDING; static final String BACKUP_TECHNOLOGY_PREFIX; static final long SECOND_MILLIS; static final List<String> sourceDateFields; }### Answer:
@Test public void shouldClearOrderFieldsOnCopy() throws Exception { Date startDate = new Date(); Date finishDate = new Date(); stubDateField(order, OrderFields.START_DATE, startDate); stubDateField(order, OrderFields.FINISH_DATE, finishDate); orderHooks.clearOrSetSpecyfiedValueOrderFieldsOnCopy(orderDD, order); verify(order).setField(OrderFields.STATE, OrderState.PENDING.getStringValue()); verify(order).setField(OrderFields.EFFECTIVE_DATE_TO, null); verify(order).setField(OrderFields.EFFECTIVE_DATE_FROM, null); verify(order).setField(OrderFields.CORRECTED_DATE_FROM, null); verify(order).setField(OrderFields.CORRECTED_DATE_TO, null); verify(order).setField(OrderFields.DONE_QUANTITY, null); verify(order).setField(OrderFields.DATE_FROM, startDate); verify(order).setField(OrderFields.DATE_TO, finishDate); } |
### Question:
OrderHooks { void setCopyOfTechnology(final Entity order) { if (orderService.isPktEnabled()) { order.setField(OrderFields.TECHNOLOGY, copyTechnology(order).orNull()); } else { Entity prototypeTechnology = order.getBelongsToField(OrderFields.TECHNOLOGY_PROTOTYPE); if (prototypeTechnology != null && TechnologyState.of(prototypeTechnology).compareTo(TechnologyState.ACCEPTED) == 0) { order.setField(OrderFields.TECHNOLOGY, prototypeTechnology); } else { order.setField(OrderFields.TECHNOLOGY, null); order.setField(OrderFields.TECHNOLOGY_PROTOTYPE, null); } } } boolean validatesWith(final DataDefinition orderDD, final Entity order); void onCreate(final DataDefinition orderDD, final Entity order); void onSave(final DataDefinition orderDD, final Entity order); void onCopy(final DataDefinition orderDD, final Entity order); void setRemainingQuantity(final Entity order); void onDelete(final DataDefinition orderDD, final Entity order); boolean setDateChanged(final DataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Entity order,
final Object fieldOldValue, final Object fieldNewValue); void setInitialState(final DataDefinition orderDD, final Entity order); boolean checkOrderDates(final DataDefinition orderDD, final Entity order); boolean checkOrderPlannedQuantity(final DataDefinition orderDD, final Entity order); void copyStartDate(final DataDefinition orderDD, final Entity order); void copyEndDate(final DataDefinition orderDD, final Entity order); boolean validateDates(final DataDefinition orderDD, final Entity order); void copyProductQuantity(final DataDefinition orderDD, final Entity order); void onCorrectingTheRequestedVolume(final DataDefinition orderDD, final Entity order); boolean neededWhenCorrectingTheRequestedVolume(); void setCommissionedPlannedQuantity(final DataDefinition orderDD, final Entity order); void setProductQuantity(final DataDefinition orderDD, final Entity order); void clearOrSetSpecyfiedValueOrderFieldsOnCopy(final DataDefinition orderDD, final Entity order); static final String L_TYPE_OF_PRODUCTION_RECORDING; static final String BACKUP_TECHNOLOGY_PREFIX; static final long SECOND_MILLIS; static final List<String> sourceDateFields; }### Answer:
@Test public final void shouldNotSetCopyOfTechnology() { given(orderService.isPktEnabled()).willReturn(true); stubBelongsToField(order, OrderFields.TECHNOLOGY, null); orderHooks.setCopyOfTechnology(order); verify(order, never()).setField(eq(OrderFields.TECHNOLOGY), notNull()); }
@Test public final void shouldSetCopyOfTechnology() { final String generatedNumber = "NEWLY GENERATED NUM"; given(technologyServiceO.generateNumberForTechnologyInOrder(eq(order), any(Entity.class))).willReturn(generatedNumber); given(orderService.isPktEnabled()).willReturn(true); DataDefinition technologyDD = mock(DataDefinition.class); Entity technology = mockEntity(technologyDD); Entity technologyCopy = mockEntity(technologyDD); given(technologyDD.copy(any(Long[].class))).willReturn(ImmutableList.of(technologyCopy)); given(technologyDD.save(any(Entity.class))).willAnswer(new Answer<Entity>() { @Override public Entity answer(final InvocationOnMock invocation) throws Throwable { return (Entity) invocation.getArguments()[0]; } }); stubBelongsToField(order, OrderFields.TECHNOLOGY, technology); stubStringField(order, OrderFields.ORDER_TYPE, OrderType.WITH_OWN_TECHNOLOGY.getStringValue()); orderHooks.setCopyOfTechnology(order); verify(order).setField(OrderFields.TECHNOLOGY, technologyCopy); verify(order, never()).setField(OrderFields.TECHNOLOGY, technology); verify(technologyCopy).setField(TechnologyFields.NUMBER, generatedNumber); } |
### Question:
OrderDetailsHooks { public void setAndDisableState(final ViewDefinitionState view) { FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM); FieldComponent stateField = (FieldComponent) view.getComponentByReference(OrderFields.STATE); stateField.setEnabled(false); if (orderForm.getEntityId() != null) { return; } stateField.setFieldValue(OrderState.PENDING.getStringValue()); } final void onBeforeRender(final ViewDefinitionState view); void fillRecipeFilterValue(final ViewDefinitionState view); final void fillProductionLine(final ViewDefinitionState view); void fillProductionLine(final LookupComponent productionLineLookup, final Entity technology,
final Entity defaultProductionLine); void generateOrderNumber(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void disableFieldOrderForm(final ViewDefinitionState view); void disableTechnologiesIfProductDoesNotAny(final ViewDefinitionState view); void setAndDisableState(final ViewDefinitionState view); void changedEnabledFieldForSpecificOrderState(final ViewDefinitionState view); void disableOrderFormForExternalItems(final ViewDefinitionState state); void filterStateChangeHistory(final ViewDefinitionState view); void disabledRibbonWhenOrderIsSynchronized(final ViewDefinitionState view); void compareDeadlineAndEndDate(final ViewDefinitionState view); void compareDeadlineAndStartDate(final ViewDefinitionState view); void setFieldsVisibility(final ViewDefinitionState view); void setFieldsVisibilityAndFill(final ViewDefinitionState view); void fillOrderDescriptionIfTechnologyHasDescription(ViewDefinitionState view); }### Answer:
@Test public void shouldSetAndDisableState() throws Exception { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(orderForm.getEntityId()).willReturn(null); orderDetailsHooks.setAndDisableState(view); verify(stateField).setEnabled(false); verify(stateField).setFieldValue(OrderState.PENDING.getStringValue()); }
@Test public void shouldDisableState() throws Exception { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(orderForm.getEntityId()).willReturn(L_ID); orderDetailsHooks.setAndDisableState(view); verify(stateField).setEnabled(false); verify(stateField, never()).setFieldValue(OrderState.PENDING.getStringValue()); } |
### Question:
MaterialsInLocationComponentModelValidators { public boolean checkMaterialFlowComponentUniqueness(final DataDefinition materialsInLocationComponentDD, final Entity materialsInLocationComponent) { Entity location = materialsInLocationComponent.getBelongsToField(LOCATION); Entity materialsInLocation = materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION); if (materialsInLocation == null || location == null) { return false; } SearchResult searchResult = materialsInLocationComponentDD.find().add(SearchRestrictions.belongsTo(LOCATION, location)) .add(SearchRestrictions.belongsTo(MATERIALS_IN_LOCATION, materialsInLocation)).list(); if (searchResult.getTotalNumberOfEntities() == 1 && !searchResult.getEntities().get(0).getId().equals(materialsInLocationComponent.getId())) { materialsInLocationComponent.addError(materialsInLocationComponentDD.getField(LOCATION), "materialFlow.validate.global.error.materialsInLocationDuplicated"); return false; } else { return true; } } boolean checkMaterialFlowComponentUniqueness(final DataDefinition materialsInLocationComponentDD,
final Entity materialsInLocationComponent); }### Answer:
@Test public void shouldReturnFalseWhenCheckMaterialFlowComponentUniquenessAndMaterialsInLocationOrLocationIsNull() { given(materialsInLocationComponent.getBelongsToField(LOCATION)).willReturn(null); given(materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION)).willReturn(null); boolean result = materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness( materialsInLocationComponentDD, materialsInLocationComponent); assertFalse(result); }
@Test public void shouldReturnFalseAndAddErrorWhenCheckMaterialFlowComponentUniquenessAndMaterialFlowComponentIsntUnique() { given(materialsInLocationComponent.getBelongsToField(LOCATION)).willReturn(location); given(materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION)).willReturn(materialsInLocation); given(materialsInLocationComponentDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(Mockito.any(SearchCriterion.class))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.list()).willReturn(searchResult); given(searchResult.getTotalNumberOfEntities()).willReturn(1); given(searchResult.getEntities()).willReturn(entities); given(entities.get(0)).willReturn(materialsInLocationComponentOther); given(materialsInLocationComponent.getId()).willReturn(L_ID); given(materialsInLocationComponentOther.getId()).willReturn(L_ID_OTHER); boolean result = materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness( materialsInLocationComponentDD, materialsInLocationComponent); assertFalse(result); Mockito.verify(materialsInLocationComponent).addError(Mockito.eq(materialsInLocationComponentDD.getField(LOCATION)), Mockito.anyString()); }
@Test public void shouldReturnTrueWhenCheckMaterialFlowComponentUniquenessAndMaterialFlowComponentIsUnique() { given(materialsInLocationComponent.getBelongsToField(LOCATION)).willReturn(location); given(materialsInLocationComponent.getBelongsToField(MATERIALS_IN_LOCATION)).willReturn(materialsInLocation); given(materialsInLocationComponentDD.find()).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.add(Mockito.any(SearchCriterion.class))).willReturn(searchCriteriaBuilder); given(searchCriteriaBuilder.list()).willReturn(searchResult); given(searchResult.getTotalNumberOfEntities()).willReturn(0); boolean result = materialsInLocationComponentModelValidators.checkMaterialFlowComponentUniqueness( materialsInLocationComponentDD, materialsInLocationComponent); assertTrue(result); } |
### Question:
OrderDetailsHooks { public void generateOrderNumber(final ViewDefinitionState view) { numberGeneratorService.generateAndInsertNumber(view, OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER, L_FORM, OrderFields.NUMBER); } final void onBeforeRender(final ViewDefinitionState view); void fillRecipeFilterValue(final ViewDefinitionState view); final void fillProductionLine(final ViewDefinitionState view); void fillProductionLine(final LookupComponent productionLineLookup, final Entity technology,
final Entity defaultProductionLine); void generateOrderNumber(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void disableFieldOrderForm(final ViewDefinitionState view); void disableTechnologiesIfProductDoesNotAny(final ViewDefinitionState view); void setAndDisableState(final ViewDefinitionState view); void changedEnabledFieldForSpecificOrderState(final ViewDefinitionState view); void disableOrderFormForExternalItems(final ViewDefinitionState state); void filterStateChangeHistory(final ViewDefinitionState view); void disabledRibbonWhenOrderIsSynchronized(final ViewDefinitionState view); void compareDeadlineAndEndDate(final ViewDefinitionState view); void compareDeadlineAndStartDate(final ViewDefinitionState view); void setFieldsVisibility(final ViewDefinitionState view); void setFieldsVisibilityAndFill(final ViewDefinitionState view); void fillOrderDescriptionIfTechnologyHasDescription(ViewDefinitionState view); }### Answer:
@Test public void shouldGenerateOrderNumber() throws Exception { orderDetailsHooks.generateOrderNumber(view); verify(numberGeneratorService).generateAndInsertNumber(view, OrdersConstants.PLUGIN_IDENTIFIER, OrdersConstants.MODEL_ORDER, L_FORM, OrderFields.NUMBER); } |
### Question:
OrderDetailsHooks { public void fillDefaultTechnology(final ViewDefinitionState view) { LookupComponent productLookup = (LookupComponent) view.getComponentByReference(OrderFields.PRODUCT); FieldComponent defaultTechnologyField = (FieldComponent) view.getComponentByReference(OrderFields.DEFAULT_TECHNOLOGY); Entity product = productLookup.getEntity(); if (product != null) { Entity defaultTechnology = technologyServiceO.getDefaultTechnology(product); if (defaultTechnology != null) { String defaultTechnologyValue = expressionService.getValue(defaultTechnology, "#number + ' - ' + #name", view.getLocale()); defaultTechnologyField.setFieldValue(defaultTechnologyValue); } } } final void onBeforeRender(final ViewDefinitionState view); void fillRecipeFilterValue(final ViewDefinitionState view); final void fillProductionLine(final ViewDefinitionState view); void fillProductionLine(final LookupComponent productionLineLookup, final Entity technology,
final Entity defaultProductionLine); void generateOrderNumber(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void disableFieldOrderForm(final ViewDefinitionState view); void disableTechnologiesIfProductDoesNotAny(final ViewDefinitionState view); void setAndDisableState(final ViewDefinitionState view); void changedEnabledFieldForSpecificOrderState(final ViewDefinitionState view); void disableOrderFormForExternalItems(final ViewDefinitionState state); void filterStateChangeHistory(final ViewDefinitionState view); void disabledRibbonWhenOrderIsSynchronized(final ViewDefinitionState view); void compareDeadlineAndEndDate(final ViewDefinitionState view); void compareDeadlineAndStartDate(final ViewDefinitionState view); void setFieldsVisibility(final ViewDefinitionState view); void setFieldsVisibilityAndFill(final ViewDefinitionState view); void fillOrderDescriptionIfTechnologyHasDescription(ViewDefinitionState view); }### Answer:
@Test public void shouldNotFillDefaultTechnologyIfThereIsNoProduct() throws Exception { given(view.getComponentByReference(OrderFields.PRODUCT)).willReturn(productLookup); given(view.getComponentByReference(OrderFields.DEFAULT_TECHNOLOGY)).willReturn(defaultTechnologyField); given(productLookup.getEntity()).willReturn(null); orderDetailsHooks.fillDefaultTechnology(view); verify(defaultTechnologyField, never()).setFieldValue(anyString()); }
@Test public void shouldNotFillDefaultTechnologyIfThereIsNoDefaultTechnology() throws Exception { given(view.getComponentByReference(OrderFields.PRODUCT)).willReturn(productLookup); given(view.getComponentByReference(OrderFields.DEFAULT_TECHNOLOGY)).willReturn(defaultTechnologyField); given(productLookup.getEntity()).willReturn(product); given(technologyServiceO.getDefaultTechnology(product)).willReturn(null); orderDetailsHooks.fillDefaultTechnology(view); verify(defaultTechnologyField, never()).setFieldValue(Mockito.anyString()); }
@Test public void shouldFillDefaultTechnology() throws Exception { given(view.getComponentByReference(OrderFields.PRODUCT)).willReturn(productLookup); given(view.getComponentByReference(OrderFields.DEFAULT_TECHNOLOGY)).willReturn(defaultTechnologyField); given(productLookup.getEntity()).willReturn(product); given(technologyServiceO.getDefaultTechnology(product)).willReturn(defaultTechnology); given(defaultTechnology.getId()).willReturn(1L); orderDetailsHooks.fillDefaultTechnology(view); verify(defaultTechnologyField).setFieldValue(anyString()); } |
### Question:
OrderDetailsHooks { public void disableFieldOrderForm(final ViewDefinitionState view) { FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM); boolean disabled = false; Long orderId = orderForm.getEntityId(); if (orderId != null) { Entity order = orderService.getOrder(orderId); if (order == null) { return; } String state = order.getStringField(OrderFields.STATE); if (!OrderState.PENDING.getStringValue().equals(state)) { disabled = true; } } orderForm.setFormEnabled(!disabled); Entity order = orderForm.getEntity(); Entity company = order.getBelongsToField(OrderFields.COMPANY); LookupComponent addressLookup = (LookupComponent) view.getComponentByReference(OrderFields.ADDRESS); if (company == null) { addressLookup.setFieldValue(null); addressLookup.setEnabled(false); } else { addressLookup.setEnabled(true); } } final void onBeforeRender(final ViewDefinitionState view); void fillRecipeFilterValue(final ViewDefinitionState view); final void fillProductionLine(final ViewDefinitionState view); void fillProductionLine(final LookupComponent productionLineLookup, final Entity technology,
final Entity defaultProductionLine); void generateOrderNumber(final ViewDefinitionState view); void fillDefaultTechnology(final ViewDefinitionState view); void disableFieldOrderForm(final ViewDefinitionState view); void disableTechnologiesIfProductDoesNotAny(final ViewDefinitionState view); void setAndDisableState(final ViewDefinitionState view); void changedEnabledFieldForSpecificOrderState(final ViewDefinitionState view); void disableOrderFormForExternalItems(final ViewDefinitionState state); void filterStateChangeHistory(final ViewDefinitionState view); void disabledRibbonWhenOrderIsSynchronized(final ViewDefinitionState view); void compareDeadlineAndEndDate(final ViewDefinitionState view); void compareDeadlineAndStartDate(final ViewDefinitionState view); void setFieldsVisibility(final ViewDefinitionState view); void setFieldsVisibilityAndFill(final ViewDefinitionState view); void fillOrderDescriptionIfTechnologyHasDescription(ViewDefinitionState view); }### Answer:
@Test public void shouldNotDisableFormIfOrderIsNotDone() throws Exception { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(orderForm.getEntityId()).willReturn(L_ID); given(orderService.getOrder(L_ID)).willReturn(order); given(orderForm.getEntity()).willReturn(order); given(order.getStringField(OrderFields.STATE)).willReturn(OrderState.PENDING.getStringValue()); given(order.getBelongsToField(OrderFields.COMPANY)).willReturn(company); orderDetailsHooks.disableFieldOrderForm(view); verify(orderForm).setFormEnabled(true); }
@Test public void shouldNotDisableFormForDoneOrder() throws Exception { given(view.getComponentByReference(L_FORM)).willReturn(orderForm); given(orderForm.getEntityId()).willReturn(L_ID); given(orderService.getOrder(L_ID)).willReturn(order); given(order.getStringField(OrderFields.STATE)).willReturn(OrderState.COMPLETED.getStringValue()); given(order.isValid()).willReturn(true); given(orderForm.getEntity()).willReturn(order); given(order.getBelongsToField(OrderFields.COMPANY)).willReturn(company); orderDetailsHooks.disableFieldOrderForm(view); verify(orderForm).setFormEnabled(false); } |
### Question:
OrderServiceImpl implements OrderService { @Override public void changeFieldState(final ViewDefinitionState view, final String booleanFieldComponentName, final String fieldComponentName) { CheckBoxComponent booleanCheckBox = (CheckBoxComponent) view.getComponentByReference(booleanFieldComponentName); FieldComponent fieldComponent = (FieldComponent) view.getComponentByReference(fieldComponentName); if (booleanCheckBox.isChecked()) { fieldComponent.setEnabled(true); fieldComponent.requestComponentUpdateState(); } else { fieldComponent.setEnabled(false); fieldComponent.requestComponentUpdateState(); } } @Override Entity getOrder(final Long orderId); @Override boolean isOrderStarted(final String state); @Override Entity getDefaultProductionLine(); @Override String makeDefaultName(final Entity product, Entity technology, final Locale locale); @Override void changeFieldState(final ViewDefinitionState view, final String booleanFieldComponentName,
final String fieldComponentName); @Override boolean checkComponentOrderHasTechnology(final DataDefinition dataDefinition, final Entity entity); @Override boolean checkAutogenealogyRequired(); @Override boolean checkRequiredBatch(final Entity order); @Override boolean isPktEnabled(); @Override String buildOrderDescription(Entity masterOrder, Entity technology, boolean fillOrderDescriptionBasedOnTechnology); }### Answer:
@Test public void shouldChangeFieldStateIfCheckboxIsSelected() { String booleanFieldComponentName = "booleanFieldComponentName"; String fieldComponentName = "fieldComponentName"; given(view.getComponentByReference(booleanFieldComponentName)).willReturn(booleanCheckBoxComponent); given(view.getComponentByReference(fieldComponentName)).willReturn(fieldComponent); given(booleanCheckBoxComponent.isChecked()).willReturn(true); orderService.changeFieldState(view, booleanFieldComponentName, fieldComponentName); verify(fieldComponent).setEnabled(true); }
@Test public void shouldntChangeFieldStateIfCheckboxIsntSelected() { String booleanFieldComponentName = "booleanFieldComponentName"; String fieldComponentName = "fieldComponentName"; given(view.getComponentByReference(booleanFieldComponentName)).willReturn(booleanCheckBoxComponent); given(view.getComponentByReference(fieldComponentName)).willReturn(fieldComponent); given(booleanCheckBoxComponent.isChecked()).willReturn(false); orderService.changeFieldState(view, booleanFieldComponentName, fieldComponentName); verify(fieldComponent).setEnabled(false); } |
### Question:
OrderStateValidationService { public void validationOnAccepted(final StateChangeContext stateChangeContext) { final List<String> references = Arrays.asList(DATE_TO, DATE_FROM, PRODUCTION_LINE); checkRequired(references, stateChangeContext); } void validationOnAccepted(final StateChangeContext stateChangeContext); void validationOnInProgress(final StateChangeContext stateChangeContext); void validationOnCompleted(final StateChangeContext stateChangeContext); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenEntityIsNullValidationAccepted() throws Exception { orderStateValidationService.validationOnAccepted(null); } |
### Question:
OrderStateValidationService { public void validationOnInProgress(final StateChangeContext stateChangeContext) { final List<String> references = Arrays.asList(DATE_TO, DATE_FROM); checkRequired(references, stateChangeContext); } void validationOnAccepted(final StateChangeContext stateChangeContext); void validationOnInProgress(final StateChangeContext stateChangeContext); void validationOnCompleted(final StateChangeContext stateChangeContext); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenEntityIsNullValidationInProgress() throws Exception { orderStateValidationService.validationOnInProgress(null); } |
### Question:
OrderStateValidationService { public void validationOnCompleted(final StateChangeContext stateChangeContext) { final List<String> fieldNames = Arrays.asList(DATE_TO, DATE_FROM, DONE_QUANTITY); checkRequired(fieldNames, stateChangeContext); } void validationOnAccepted(final StateChangeContext stateChangeContext); void validationOnInProgress(final StateChangeContext stateChangeContext); void validationOnCompleted(final StateChangeContext stateChangeContext); }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenEntityIsNullValidationCompleted() throws Exception { orderStateValidationService.validationOnCompleted(null); }
@Test public void shouldPerformValidationCompleted() throws Exception { given(order.getField(Mockito.anyString())).willReturn("fieldValue"); given(order.getField(EFFECTIVE_DATE_FROM)).willReturn(new Date(System.currentTimeMillis() - 10000)); orderStateValidationService.validationOnCompleted(stateChangeContext); verify(stateChangeContext, never()).addFieldValidationError(Mockito.anyString(), Mockito.eq(L_MISSING_MESSAGE)); verify(stateChangeContext, never()).addFieldValidationError(Mockito.anyString(), Mockito.eq(L_WRONG_EFFECTIVE_DATE_TO)); } |
### Question:
TransferModelValidators { public boolean validateTransfer(final DataDefinition transferDD, final Entity transfer) { boolean isValid = true; boolean result = true; String type = transfer.getStringField(TYPE); Date time = (Date) transfer.getField(TIME); if (type == null) { transfer.addError(transferDD.getField(TYPE), L_MATERIAL_FLOW_VALIDATE_GLOBAL_ERROR_FILL_TYPE); isValid = false; } else { result = validateLocation(transferDD, transfer, type); } if (time == null) { transfer.addError(transferDD.getField(TIME), L_MATERIAL_FLOW_VALIDATE_GLOBAL_ERROR_FILL_DATE); isValid = false; } if (isValid) { isValid = result; } return isValid; } boolean validateTransfer(final DataDefinition transferDD, final Entity transfer); boolean checkIfLocationFromOrLocationToHasExternalNumber(final DataDefinition transferDD, final Entity transfer); }### Answer:
@Test public void shouldReturnFalseAndAddErrorWhenValidateTransferAndAllFieldsAreNull() { given(transfer.getStringField(TYPE)).willReturn(null); given(transfer.getField(TIME)).willReturn(null); given(transfer.getBelongsToField(LOCATION_FROM)).willReturn(null); given(transfer.getBelongsToField(LOCATION_TO)).willReturn(null); boolean result = transferModelValidators.validateTransfer(transferDD, transfer); assertFalse(result); verify(transfer, times(2)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnFalseAndAddErrorWhenValidateTransferAndTypeIsNull() { given(transfer.getStringField(TYPE)).willReturn(null); given(transfer.getField(TIME)).willReturn(time); given(transfer.getBelongsToField(LOCATION_FROM)).willReturn(locationFrom); given(transfer.getBelongsToField(LOCATION_TO)).willReturn(locationTo); boolean result = transferModelValidators.validateTransfer(transferDD, transfer); assertFalse(result); verify(transfer, times(1)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnFalseAndAddErrorWhenValidateTransferAndTimeIsNull() { given(transfer.getStringField(TYPE)).willReturn(TRANSPORT.getStringValue()); given(transfer.getField(TIME)).willReturn(null); given(transfer.getBelongsToField(LOCATION_FROM)).willReturn(locationFrom); given(transfer.getBelongsToField(LOCATION_TO)).willReturn(locationTo); boolean result = transferModelValidators.validateTransfer(transferDD, transfer); assertFalse(result); verify(transfer, times(1)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnFalseAndAddErrorWhenValidateTransferAndLocationsAreNull() { given(transfer.getStringField(TYPE)).willReturn(TRANSPORT.getStringValue()); given(transfer.getField(TIME)).willReturn(time); given(transfer.getBelongsToField(LOCATION_FROM)).willReturn(null); given(transfer.getBelongsToField(LOCATION_TO)).willReturn(null); boolean result = transferModelValidators.validateTransfer(transferDD, transfer); assertFalse(result); verify(transfer, times(2)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnTrueWhenValidateTransferAndAllFieldsArentNull() { given(transfer.getStringField(TYPE)).willReturn(TRANSPORT.getStringValue()); given(transfer.getField(TIME)).willReturn(time); given(transfer.getBelongsToField(LOCATION_FROM)).willReturn(locationFrom); given(transfer.getBelongsToField(LOCATION_TO)).willReturn(locationTo); boolean result = transferModelValidators.validateTransfer(transferDD, transfer); assertTrue(result); verify(transfer, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } |
### Question:
OrderStateChangeReasonService { public boolean neededWhenCorrectingDateFrom() { return parameterService.getParameter().getBooleanField(REASON_NEEDED_WHEN_CORRECTING_DATE_FROM); } boolean neededWhenCorrectingDateFrom(); boolean neededWhenCorrectingDateTo(); boolean neededForDecline(); boolean neededForInterrupt(); boolean neededForAbandon(); boolean neededWhenChangingEffectiveDateFrom(); long getEffectiveDateFromDifference(final Entity parameter, final Entity order); long getEffectiveDateToDifference(final Entity parameter, final Entity order); void showReasonForm(final StateChangeContext stateChangeContext, final ViewContextHolder viewContext); }### Answer:
@Test public void shouldReturnTrueIfIsReasonNeededWhenCorrectingDateFrom() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CORRECTING_DATE_FROM)).willReturn(true); boolean result = orderStateChangeReasonService.neededWhenCorrectingDateFrom(); assertTrue(result); }
@Test public void shouldReturnFalseIfIsReasonNeededWhenCorrectingDateFrom() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CORRECTING_DATE_FROM)).willReturn(false); boolean result = orderStateChangeReasonService.neededWhenCorrectingDateFrom(); assertFalse(result); } |
### Question:
OrderStateChangeReasonService { public boolean neededWhenCorrectingDateTo() { return parameterService.getParameter().getBooleanField(REASON_NEEDED_WHEN_CORRECTING_DATE_TO); } boolean neededWhenCorrectingDateFrom(); boolean neededWhenCorrectingDateTo(); boolean neededForDecline(); boolean neededForInterrupt(); boolean neededForAbandon(); boolean neededWhenChangingEffectiveDateFrom(); long getEffectiveDateFromDifference(final Entity parameter, final Entity order); long getEffectiveDateToDifference(final Entity parameter, final Entity order); void showReasonForm(final StateChangeContext stateChangeContext, final ViewContextHolder viewContext); }### Answer:
@Test public void shouldReturnTrueIfIsReasonNeededWhenCorrectingDateTo() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CORRECTING_DATE_TO)).willReturn(true); boolean result = orderStateChangeReasonService.neededWhenCorrectingDateTo(); assertTrue(result); }
@Test public void shouldReturnFalseIfIsReasonNeededWhenCorrectingDateTo() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CORRECTING_DATE_TO)).willReturn(false); boolean result = orderStateChangeReasonService.neededWhenCorrectingDateTo(); assertFalse(result); } |
### Question:
OrderStateChangeReasonService { public boolean neededForDecline() { return parameterService.getParameter().getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_DECLINED); } boolean neededWhenCorrectingDateFrom(); boolean neededWhenCorrectingDateTo(); boolean neededForDecline(); boolean neededForInterrupt(); boolean neededForAbandon(); boolean neededWhenChangingEffectiveDateFrom(); long getEffectiveDateFromDifference(final Entity parameter, final Entity order); long getEffectiveDateToDifference(final Entity parameter, final Entity order); void showReasonForm(final StateChangeContext stateChangeContext, final ViewContextHolder viewContext); }### Answer:
@Test public void shouldReturnTrueIfIsReasonNeededWhenChangingStateToDeclined() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_DECLINED)).willReturn(true); boolean result = orderStateChangeReasonService.neededForDecline(); assertTrue(result); }
@Test public void shouldReturnFalseIfIsReasonNeededWhenChangingStateToDeclined() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_DECLINED)).willReturn(false); boolean result = orderStateChangeReasonService.neededForDecline(); assertFalse(result); } |
### Question:
OrderStateChangeReasonService { public boolean neededForInterrupt() { return parameterService.getParameter().getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_INTERRUPTED); } boolean neededWhenCorrectingDateFrom(); boolean neededWhenCorrectingDateTo(); boolean neededForDecline(); boolean neededForInterrupt(); boolean neededForAbandon(); boolean neededWhenChangingEffectiveDateFrom(); long getEffectiveDateFromDifference(final Entity parameter, final Entity order); long getEffectiveDateToDifference(final Entity parameter, final Entity order); void showReasonForm(final StateChangeContext stateChangeContext, final ViewContextHolder viewContext); }### Answer:
@Test public void shouldReturnTrueIfIsReasonNeededWhenChangingStateToInterrupted() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_INTERRUPTED)).willReturn(true); boolean result = orderStateChangeReasonService.neededForInterrupt(); assertTrue(result); }
@Test public void shouldReturnFalseIfIsReasonNeededWhenChangingStateToInterrupted() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_INTERRUPTED)).willReturn(false); boolean result = orderStateChangeReasonService.neededForInterrupt(); assertFalse(result); } |
### Question:
OrderStateChangeReasonService { public boolean neededForAbandon() { return parameterService.getParameter().getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_ABANDONED); } boolean neededWhenCorrectingDateFrom(); boolean neededWhenCorrectingDateTo(); boolean neededForDecline(); boolean neededForInterrupt(); boolean neededForAbandon(); boolean neededWhenChangingEffectiveDateFrom(); long getEffectiveDateFromDifference(final Entity parameter, final Entity order); long getEffectiveDateToDifference(final Entity parameter, final Entity order); void showReasonForm(final StateChangeContext stateChangeContext, final ViewContextHolder viewContext); }### Answer:
@Test public void shouldReturnTrueIfIsReasonNeededWhenChangingStateToAbandoned() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_ABANDONED)).willReturn(true); boolean result = orderStateChangeReasonService.neededForAbandon(); assertTrue(result); }
@Test public void shouldReturnFalseIfIsReasonNeededWhenChangingStateToAbandoned() { Entity parameter = mock(Entity.class); given(parameterService.getParameter()).willReturn(parameter); given(parameter.getBooleanField(REASON_NEEDED_WHEN_CHANGING_STATE_TO_ABANDONED)).willReturn(false); boolean result = orderStateChangeReasonService.neededForAbandon(); assertFalse(result); } |
### Question:
AssignmentToShiftReportDetailsHooks { public void generateAssignmentToShiftReportNumber(final ViewDefinitionState view) { numberGeneratorService.generateAndInsertNumber(view, AssignmentToShiftConstants.PLUGIN_IDENTIFIER, AssignmentToShiftConstants.MODEL_ASSIGNMENT_TO_SHIFT_REPORT, L_FORM, AssignmentToShiftReportFields.NUMBER); } void generateAssignmentToShiftReportNumber(final ViewDefinitionState view); void disableFields(final ViewDefinitionState view); }### Answer:
@Test public void shouldGenerateAssignmentToShiftReportNumber() { hooks.generateAssignmentToShiftReportNumber(view); verify(numberGeneratorService).generateAndInsertNumber(view, AssignmentToShiftConstants.PLUGIN_IDENTIFIER, AssignmentToShiftConstants.MODEL_ASSIGNMENT_TO_SHIFT_REPORT, L_FORM, AssignmentToShiftReportFields.NUMBER); } |
### Question:
AssignmentToShiftReportHooks { public boolean checkIfIsMoreThatFiveDays(final DataDefinition assignmentToShiftReportDD, final Entity assignmentToShiftReport) { int days = assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport); if (days > 5) { assignmentToShiftReport.addError(assignmentToShiftReportDD.getField(DATE_FROM), "assignmentToShift.assignmentToShift.report.onlyFiveDays"); assignmentToShiftReport.addError(assignmentToShiftReportDD.getField(DATE_TO), "assignmentToShift.assignmentToShift.report.onlyFiveDays"); return false; } return true; } boolean checkIfIsMoreThatFiveDays(final DataDefinition assignmentToShiftReportDD, final Entity assignmentToShiftReport); void clearGenerated(final DataDefinition assignmentToShiftReportDD, final Entity assignmentToShiftReport); final boolean validateDates(final DataDefinition dataDefinition, final Entity assignmentToShiftReport); }### Answer:
@Test public void shouldReturnFalseWhenCheckIfIsMoreThatFiveDays() { given(assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport)).willReturn(10); boolean result = hooks.checkIfIsMoreThatFiveDays(assignmentToShiftReportDD, assignmentToShiftReport); Assert.assertFalse(result); verify(assignmentToShiftReport, times(2)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnTrueWhenCheckIfIsMoreThatFiveDays() { given(assignmentToShiftXlsHelper.getNumberOfDaysBetweenGivenDates(assignmentToShiftReport)).willReturn(3); boolean result = hooks.checkIfIsMoreThatFiveDays(assignmentToShiftReportDD, assignmentToShiftReport); Assert.assertTrue(result); verify(assignmentToShiftReport, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } |
### Question:
AssignmentToShiftReportHooks { public void clearGenerated(final DataDefinition assignmentToShiftReportDD, final Entity assignmentToShiftReport) { assignmentToShiftReport.setField(GENERATED, false); assignmentToShiftReport.setField(FILE_NAME, null); } boolean checkIfIsMoreThatFiveDays(final DataDefinition assignmentToShiftReportDD, final Entity assignmentToShiftReport); void clearGenerated(final DataDefinition assignmentToShiftReportDD, final Entity assignmentToShiftReport); final boolean validateDates(final DataDefinition dataDefinition, final Entity assignmentToShiftReport); }### Answer:
@Test public void shouldClearGenerated() { hooks.clearGenerated(assignmentToShiftReportDD, assignmentToShiftReport); verify(assignmentToShiftReport, times(2)).setField(Mockito.anyString(), Mockito.any()); } |
### Question:
StaffAssignmentToShiftHooks { public void setOccupationTypeForGridValue(final DataDefinition staffAssignmentToShiftDD, final Entity staffAssignmentToShift) { String occupationType = staffAssignmentToShift.getStringField(StaffAssignmentToShiftFields.OCCUPATION_TYPE); Entity dictionaryItem = assignmentToShiftDetailsHooks.findDictionaryItemByName(occupationType); String technicalCode = dictionaryItem.getStringField(TECHNICAL_CODE); if (technicalCode != null && technicalCode.equals(WORK_ON_LINE.getStringValue())) { if (staffAssignmentToShift.getBelongsToField(StaffAssignmentToShiftFields.PRODUCTION_LINE) == null) { staffAssignmentToShift.addError(staffAssignmentToShiftDD.getField(StaffAssignmentToShiftFields.PRODUCTION_LINE), "assignmentToShift.staffAssignmentToShift.productionLine.isEmpty"); return; } staffAssignmentToShift.setField(StaffAssignmentToShiftFields.OCCUPATION_TYPE_VALUE_FOR_GRID, occupationType + ": " + staffAssignmentToShift.getBelongsToField(StaffAssignmentToShiftFields.PRODUCTION_LINE) .getStringField(NUMBER)); } else if (technicalCode != null && technicalCode.equals(OTHER_CASE.getStringValue())) { String occupationTypeName = staffAssignmentToShift.getStringField(StaffAssignmentToShiftFields.OCCUPATION_TYPE_NAME); if (StringUtils.isEmpty(occupationTypeName)) { staffAssignmentToShift.setField(StaffAssignmentToShiftFields.OCCUPATION_TYPE_VALUE_FOR_GRID, occupationType); } else { staffAssignmentToShift.setField(StaffAssignmentToShiftFields.OCCUPATION_TYPE_VALUE_FOR_GRID, occupationType + ": " + occupationTypeName); } } else { staffAssignmentToShift.setField(StaffAssignmentToShiftFields.OCCUPATION_TYPE_VALUE_FOR_GRID, occupationType); } } void onSave(final DataDefinition staffAssignmentToShiftDD, final Entity staffAssignmentToShift); Boolean onCopy(final DataDefinition staffAssignmentToShiftDD, final Entity staffAssignmentToShift); void setOccupationTypeForGridValue(final DataDefinition staffAssignmentToShiftDD, final Entity staffAssignmentToShift); void setOccupationTypeEnum(final DataDefinition staffAssignmentToShiftDD, final Entity staffAssignmentToShift); }### Answer:
@Test public void shouldSaveOccupationTypeForGridValueWhenProductionLineIsSelected() { String technicalCode = "01workOnLine"; String occupationType = "Praca na linii"; String productionLineNumber = "00001"; String occupationTypeForGridValue = "info"; given(staffAssignmentToShift.getStringField(OCCUPATION_TYPE)).willReturn(occupationType); given(staffAssignmentToShiftDetailsHooks.findDictionaryItemByName(occupationType)).willReturn(dictionary); given(dictionary.getStringField(TECHNICAL_CODE)).willReturn(technicalCode); given(staffAssignmentToShift.getBelongsToField(PRODUCTION_LINE)).willReturn(productionLine); given(productionLine.getStringField(NUMBER)).willReturn(productionLineNumber); hooks.setOccupationTypeForGridValue(staffAssignmentToShiftDD, staffAssignmentToShift); Assert.assertEquals("info", occupationTypeForGridValue); }
@Test public void shouldAddErrorForEntityWhenProductionLineIsNull() { String technicalCode = "01workOnLine"; String occupationType = "Praca na linii"; given(staffAssignmentToShift.getStringField(OCCUPATION_TYPE)).willReturn(occupationType); given(staffAssignmentToShiftDetailsHooks.findDictionaryItemByName(occupationType)).willReturn(dictionary); given(dictionary.getStringField(TECHNICAL_CODE)).willReturn(technicalCode); given(staffAssignmentToShift.getBelongsToField(PRODUCTION_LINE)).willReturn(null); hooks.setOccupationTypeForGridValue(staffAssignmentToShiftDD, staffAssignmentToShift); verify(staffAssignmentToShift).addError(staffAssignmentToShiftDD.getField(StaffAssignmentToShiftFields.PRODUCTION_LINE), "assignmentToShift.staffAssignmentToShift.productionLine.isEmpty"); } |
### Question:
AssignmentToShiftHooks { void setInitialState(final Entity assignmentToShift) { stateChangeEntityBuilder.buildInitial(describer, assignmentToShift, AssignmentToShiftState.DRAFT); } void onCreate(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); void onCopy(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); boolean onValidate(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); }### Answer:
@Test public void shouldSetInitialState() { assignmentToShiftHooks.setInitialState(assignmentToShift); verify(stateChangeEntityBuilder).buildInitial(describer, assignmentToShift, AssignmentToShiftState.DRAFT); } |
### Question:
AssignmentToShiftHooks { boolean checkUniqueEntity(final Entity assignmentToShift) { Date startDate = assignmentToShift.getDateField(AssignmentToShiftFields.START_DATE); Entity shift = assignmentToShift.getBelongsToField(AssignmentToShiftFields.SHIFT); Entity factory = assignmentToShift.getBelongsToField(AssignmentToShiftFields.FACTORY); Entity crew = assignmentToShift.getBelongsToField(AssignmentToShiftFields.CREW); AssignmentToShiftCriteria criteria = AssignmentToShiftCriteria.empty(); SearchCriterion additionalCriteria = eq(AssignmentToShiftFields.START_DATE, startDate); criteria.withShiftCriteria(idEq(shift.getId())); criteria.withFactoryCriteria(idEq(factory.getId())); if (crew != null) { criteria.withCrewCriteria(idEq(crew.getId())); } else { additionalCriteria = and(additionalCriteria, isNull(AssignmentToShiftFields.CREW)); } if (assignmentToShift.getId() != null) { additionalCriteria = and(additionalCriteria, idNe(assignmentToShift.getId())); } criteria.withCriteria(additionalCriteria); for (Entity matchingAssignment : assignmentToShiftDataProvider.find(criteria, Optional.of(alias(id(), "id"))).asSet()) { addErrorMessages(assignmentToShift.getDataDefinition(), assignmentToShift); return false; } return true; } void onCreate(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); void onCopy(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); boolean onValidate(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); }### Answer:
@Test public void shouldReturnTrueWhenCheckUniqueEntityIfEntityIsNotSaved() { boolean result = assignmentToShiftHooks.checkUniqueEntity(assignmentToShift); Assert.assertTrue(result); verify(assignmentToShift, never()).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnFalseWhenCheckUniqueEntityIfEntityIsntSaved() { stubFind(mockEntity()); boolean result = assignmentToShiftHooks.checkUniqueEntity(assignmentToShift); Assert.assertFalse(result); verify(assignmentToShift, times(4)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); }
@Test public void shouldReturnFalseWhenCheckUniqueEntityIfEntityIsSaved() { stubFind(mockEntity()); boolean result = assignmentToShiftHooks.checkUniqueEntity(assignmentToShift); Assert.assertFalse(result); verify(assignmentToShift, times(4)).addError(Mockito.any(FieldDefinition.class), Mockito.anyString()); } |
### Question:
AssignmentToShiftHooks { void setNextDay(final Entity assignmentToShift) { Optional<LocalDate> maybeNewDate = resolveNextStartDate(assignmentToShift); assignmentToShift.setField(AssignmentToShiftFields.START_DATE, maybeNewDate.transform(TO_DATE).orNull()); } void onCreate(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); void onCopy(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); boolean onValidate(final DataDefinition assignmentToShiftDD, final Entity assignmentToShift); }### Answer:
@Test public final void shouldPickUpNextDay() { Entity startProjection1 = mockStartDateProjection(START_DATE.plusDays(1)); Entity startProjection2 = mockStartDateProjection(START_DATE.plusDays(2)); Entity startProjection3 = mockStartDateProjection(START_DATE.plusDays(3)); stubFindAll(Lists.newArrayList(startProjection1, startProjection2, startProjection3)); given(shiftPojo.worksAt(START_DATE)).willReturn(true); given(shiftPojo.worksAt(START_DATE.plusDays(1))).willReturn(false); given(shiftPojo.worksAt(START_DATE.plusDays(2))).willReturn(true); given(shiftPojo.worksAt(START_DATE.plusDays(3))).willReturn(false); given(shiftPojo.worksAt(START_DATE.plusDays(4))).willReturn(false); given(shiftPojo.worksAt(START_DATE.plusDays(5))).willReturn(true); assignmentToShiftHooks.setNextDay(assignmentToShift); ArgumentCaptor<Date> dateCaptor = ArgumentCaptor.forClass(Date.class); verify(assignmentToShift).setField(eq(AssignmentToShiftFields.START_DATE), dateCaptor.capture()); Date pickedUpNextStartDate = dateCaptor.getValue(); Assert.assertTrue(START_DATE.plusDays(5).toDate().compareTo(pickedUpNextStartDate) == 0); }
@Test public final void shouldPickUpNextDayIfThereIsNoOccupiedDates() { given(shiftPojo.worksAt(START_DATE)).willReturn(true); given(shiftPojo.worksAt(START_DATE.plusDays(1))).willReturn(false); given(shiftPojo.worksAt(START_DATE.plusDays(2))).willReturn(true); given(shiftPojo.worksAt(START_DATE.plusDays(3))).willReturn(false); given(shiftPojo.worksAt(START_DATE.plusDays(4))).willReturn(false); given(shiftPojo.worksAt(START_DATE.plusDays(5))).willReturn(true); assignmentToShiftHooks.setNextDay(assignmentToShift); ArgumentCaptor<Date> dateCaptor = ArgumentCaptor.forClass(Date.class); verify(assignmentToShift).setField(eq(AssignmentToShiftFields.START_DATE), dateCaptor.capture()); Date pickedUpNextStartDate = dateCaptor.getValue(); Assert.assertTrue(START_DATE.plusDays(2).toDate().compareTo(pickedUpNextStartDate) == 0); }
@Test public final void shouldNotPickUpAnyDateIfShiftNeverWork() { Entity startProjection1 = mockStartDateProjection(START_DATE.plusDays(1)); Entity startProjection2 = mockStartDateProjection(START_DATE.plusDays(2)); Entity startProjection3 = mockStartDateProjection(START_DATE.plusDays(3)); stubFindAll(Lists.newArrayList(startProjection1, startProjection2, startProjection3)); assignmentToShiftHooks.setNextDay(assignmentToShift); verify(assignmentToShift).setField(eq(AssignmentToShiftFields.START_DATE), refEq(null)); } |
### Question:
StaffAssignmentToShiftDetailsHooks { public void setFieldsEnabledWhenTypeIsSpecific(final ViewDefinitionState view) { FieldComponent occupationType = (FieldComponent) view.getComponentByReference(OCCUPATION_TYPE); Entity dictionaryItem = findDictionaryItemByName(occupationType.getFieldValue().toString()); if (dictionaryItem == null) { setFieldsEnabled(view, false, false); } else { String occupationTypeTechnicalCode = dictionaryItem.getStringField(TECHNICAL_CODE); if (WORK_ON_LINE.getStringValue().equals(occupationTypeTechnicalCode)) { setFieldsEnabled(view, true, false); } else if (OTHER_CASE.getStringValue().equals(occupationTypeTechnicalCode)) { setFieldsEnabled(view, false, true); } else { setFieldsEnabled(view, false, false); } } } void setCriteriaModifiers(final ViewDefinitionState view); void setFieldsEnabledWhenTypeIsSpecific(final ViewDefinitionState view); void setOccupationTypeToDefault(final ViewDefinitionState view); }### Answer:
@Test public void shouldEnabledProductionLineAndDisableOccupationTypeNameFieldsWhenWorkOnLineIsSelected() { String dictionaryName = "Praca na linii"; String technicalCode = "01workOnLine"; given(occupationType.getFieldValue()).willReturn(dictionaryName); SearchCriterion criterion = SearchRestrictions.eq(NAME, dictionaryName); given(builder.add(criterion)).willReturn(builder); given(builder.uniqueResult()).willReturn(dictionary); given(dictionary.getStringField(TECHNICAL_CODE)).willReturn(technicalCode); detailsHooks.setFieldsEnabledWhenTypeIsSpecific(view); verify(productionLine).setVisible(true); verify(occupationTypeName).setVisible(false); }
@Test public void shouldDisabledProductionLineAndEnableOccupationTypeNameFieldsWhenOtherCaseIsSelected() { String dictionaryName = "Inne zadania"; String technicalCode = "02otherCase"; given(occupationType.getFieldValue()).willReturn(dictionaryName); SearchCriterion criterion = SearchRestrictions.eq(NAME, dictionaryName); given(builder.add(criterion)).willReturn(builder); given(builder.uniqueResult()).willReturn(dictionary); given(dictionary.getStringField(TECHNICAL_CODE)).willReturn(technicalCode); detailsHooks.setFieldsEnabledWhenTypeIsSpecific(view); verify(productionLine).setVisible(false); verify(occupationTypeName).setVisible(true); }
@Test public void shouldDisabledProductionLineAndOccupationTypeNameFieldsWhenMixDictionaryIsSelected() { String dictionaryName = "MIX"; given(occupationType.getFieldValue()).willReturn(dictionaryName); SearchCriterion criterion = SearchRestrictions.eq(NAME, dictionaryName); given(builder.add(criterion)).willReturn(builder); given(builder.uniqueResult()).willReturn(dictionary); given(dictionary.getStringField(TECHNICAL_CODE)).willReturn(Mockito.anyString()); detailsHooks.setFieldsEnabledWhenTypeIsSpecific(view); verify(productionLine).setVisible(false); verify(occupationTypeName).setVisible(false); }
@Test public void shouldDisabledProductionLineAndOccupationTypeNameFieldsWhenEmptyIsSelected() { String dictionaryName = ""; given(occupationType.getFieldValue()).willReturn(dictionaryName); SearchCriterion criterion = SearchRestrictions.eq(NAME, dictionaryName); given(builder.add(criterion)).willReturn(builder); given(builder.uniqueResult()).willReturn(null); detailsHooks.setFieldsEnabledWhenTypeIsSpecific(view); verify(productionLine).setVisible(false); verify(occupationTypeName).setVisible(false); } |
### Question:
StaffAssignmentToShiftDetailsHooks { public void setOccupationTypeToDefault(final ViewDefinitionState view) { FormComponent staffAssignmentToShiftForm = (FormComponent) view.getComponentByReference("form"); FieldComponent occupationType = (FieldComponent) view.getComponentByReference(OCCUPATION_TYPE); if ((staffAssignmentToShiftForm.getEntityId() == null) && (occupationType.getFieldValue() == null)) { Entity dictionaryItem = findDictionaryItemByTechnicalCode(WORK_ON_LINE.getStringValue()); if (dictionaryItem != null) { String occupationTypeName = dictionaryItem.getStringField(NAME); occupationType.setFieldValue(occupationTypeName); occupationType.requestComponentUpdateState(); } } } void setCriteriaModifiers(final ViewDefinitionState view); void setFieldsEnabledWhenTypeIsSpecific(final ViewDefinitionState view); void setOccupationTypeToDefault(final ViewDefinitionState view); }### Answer:
@Test public void shouldntSetOccupationTypeToDefaultWhenFormIsSaved() { String dictionaryName = "Praca na linii"; given(staffAssignmentToShiftForm.getEntityId()).willReturn(1L); given(occupationType.getFieldValue()).willReturn(dictionaryName); detailsHooks.setOccupationTypeToDefault(view); verify(occupationType, never()).setFieldValue(Mockito.anyString()); }
@Test public void shouldntSetOccupationTypeToDefaultWhenDictionaryIsNull() { given(staffAssignmentToShiftForm.getEntityId()).willReturn(null); given(occupationType.getFieldValue()).willReturn(null); SearchCriterion criterion = SearchRestrictions.eq(TECHNICAL_CODE, WORK_ON_LINE.getStringValue()); given(builder.add(criterion)).willReturn(builder); given(builder.uniqueResult()).willReturn(null); detailsHooks.setOccupationTypeToDefault(view); verify(occupationType, never()).setFieldValue(Mockito.anyString()); }
@Test public void shouldSetOccupationTypeToDefaultWhenDictionary() { given(staffAssignmentToShiftForm.getEntityId()).willReturn(null); given(occupationType.getFieldValue()).willReturn(null); SearchCriterion criterion = SearchRestrictions.eq(TECHNICAL_CODE, WORK_ON_LINE.getStringValue()); given(builder.add(criterion)).willReturn(builder); given(builder.uniqueResult()).willReturn(dictionary); given(dictionary.getStringField(NAME)).willReturn(Mockito.anyString()); detailsHooks.setOccupationTypeToDefault(view); verify(occupationType).setFieldValue(Mockito.anyString()); } |
### Question:
TechnologyListenersTN { public void checkOperationOutputQuantities(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent technologyForm = (FormComponent) view.getComponentByReference(L_FORM); if (technologyForm.getEntityId() == null) { return; } Entity technology = technologyForm.getEntity(); if (!TechnologyState.DRAFT.getStringValue().equals(technology.getStringField(TechnologyFields.STATE))) { return; } technology = technology.getDataDefinition().get(technology.getId()); List<String> messages = normService.checkOperationOutputQuantities(technology); if (!messages.isEmpty()) { StringBuilder builder = new StringBuilder(); for (String message : messages) { builder.append(message); builder.append(", "); } technologyForm.addMessage("technologies.technology.validate.error.invalidQuantity", MessageType.INFO, false, builder.toString()); } } void checkOperationOutputQuantities(final ViewDefinitionState view, final ComponentState componentState,
final String[] args); }### Answer:
@Test public void shouldReturnIfTheTechnologyIsntInDraftState() { given(view.getComponentByReference("form")).willReturn(form); given(form.getEntity()).willReturn(technology); given(technology.getStringField("state")).willReturn("02accepted"); technologyListenersTN.checkOperationOutputQuantities(view, componentState, null); verify(normService, never()).checkOperationOutputQuantities(technology); verify(form, never()).addMessage(Mockito.anyString(), Mockito.eq(MessageType.INFO), Mockito.eq(false)); }
@Ignore @Test public void shouldPassValidationErrorsToTheEntityForAcceptedTechnology() { given(view.getComponentByReference("form")).willReturn(form); given(form.getEntity()).willReturn(technology); given(technology.getStringField("state")).willReturn("01draft"); given(technology.getDataDefinition()).willReturn(dataDefinition); given(technology.getId()).willReturn(0L); given(dataDefinition.get(0L)).willReturn(technology); technologyListenersTN.checkOperationOutputQuantities(view, componentState, null); verify(form).addMessage(Mockito.eq("err1"), Mockito.eq(MessageType.INFO), Mockito.eq(false)); verify(form).addMessage(Mockito.eq("err2"), Mockito.eq(MessageType.INFO), Mockito.eq(false)); } |
### Question:
TechnologyOperationComponentDetailsHooks { public void checkOperationOutputQuantities(final ViewDefinitionState view) { FormComponent form = (FormComponent) view.getComponentByReference("form"); if (form.getEntityId() == null) { return; } Entity operationComponent = form.getEntity(); operationComponent = operationComponent.getDataDefinition().get(operationComponent.getId()); BigDecimal timeNormsQuantity = operationComponent.getDecimalField("productionInOneCycle"); Entity productOutComponent = null; try { productOutComponent = technologyService.getMainOutputProductComponent(operationComponent); } catch (IllegalStateException e) { return; } BigDecimal currentQuantity = productOutComponent.getDecimalField("quantity"); if (timeNormsQuantity != null && timeNormsQuantity.compareTo(currentQuantity) != 0) { form.addMessage("technologies.technologyOperationComponent.validate.error.invalidQuantity", MessageType.INFO, false, numberService.format(currentQuantity), productOutComponent.getBelongsToField("product").getStringField("unit")); } } void checkOperationOutputQuantities(final ViewDefinitionState view); void updateNextOperationAfterProducedQuantityFieldStateonWindowLoad(final ViewDefinitionState viewDefinitionState); void updateFieldsStateOnWindowLoad(final ViewDefinitionState viewDefinitionState); void fillUnitFields(final ViewDefinitionState view); }### Answer:
@Test public void shouldNotFreakOutWhenTheOutputProductComponentCannotBeFound() { given(technologyService.getMainOutputProductComponent(opComp1)).willThrow(new IllegalStateException()); technologyOperationComponentDetailsHooks.checkOperationOutputQuantities(view); }
@Ignore @Test public void shouldAttachCorrectErrorToTheRightComponentIfQuantitiesAreDifferent() { String number = decimalFormat.format(prodComp1.getDecimalField("quantity")); technologyOperationComponentDetailsHooks.checkOperationOutputQuantities(view); verify(productionInOneCycle).addMessage(Mockito.anyString(), MessageType.FAILURE); }
@Test public void shouldNotGiveAnyErrorIfQuantitiesAreTheSame() { given(prodComp1.getDecimalField("quantity")).willReturn(new BigDecimal(1.1f)); given(opComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(1.1f)); technologyOperationComponentDetailsHooks.checkOperationOutputQuantities(view); verify(productionInOneCycle, Mockito.never()).addMessage(Mockito.anyString(), Mockito.eq(MessageType.FAILURE)); } |
### Question:
TechnologyStateChangeListenerServiceTNFO { public boolean checkOperationOutputQuantities(final StateChangeContext stateChangeContext) { Entity techology = stateChangeContext.getOwner(); Entity technology = techology.getDataDefinition().get(techology.getId()); List<String> messages = normService.checkOperationOutputQuantities(technology); if (!messages.isEmpty()) { stateChangeContext.addValidationError("technologies.technology.validate.global.error.treeIsNotValid"); StringBuilder builder = new StringBuilder(); for (String message : messages) { builder.append(message); builder.append(", "); } stateChangeContext.addMessage("technologies.technology.validate.error.invalidQuantity", StateMessageType.FAILURE, false, builder.toString()); } return messages.isEmpty(); } boolean checkOperationOutputQuantities(final StateChangeContext stateChangeContext); boolean checkIfAllOperationComponenthHaveTJSet(final StateChangeContext stateChangeContext); }### Answer:
@Test public void shouldAlwaysPassIfTheTechnologyIsInDraftState() { given(stateChangeContext.getOwner()).willReturn(technology); given(technology.getDataDefinition()).willReturn(dataDefinition); given(technology.getStringField("state")).willReturn("01draft"); boolean isValid = technologyStateChangeListenerServiceTNFO.checkOperationOutputQuantities(stateChangeContext); assertTrue(isValid); } |
### Question:
NormService { public List<String> checkOperationOutputQuantities(final Entity technology) { List<String> messages = Lists.newArrayList(); List<Entity> operationComponents = technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS); for (Entity operationComponent : operationComponents) { BigDecimal timeNormsQuantity = getProductionInOneCycle(operationComponent); BigDecimal currentQuantity; try { currentQuantity = technologyService.getProductCountForOperationComponent(operationComponent); } catch (IllegalStateException e) { continue; } if (timeNormsQuantity == null || timeNormsQuantity.compareTo(currentQuantity) != 0) { String nodeNumber = operationComponent.getStringField(TechnologyOperationComponentFields.NODE_NUMBER); if (nodeNumber == null) { Entity operation = operationComponent.getBelongsToField(TechnologyOperationComponentFields.OPERATION); if (operation != null) { String name = operation.getStringField(OperationFields.NAME); if (name != null) { messages.add(name); } } } else { messages.add(nodeNumber); } } } return messages; } List<String> checkOperationOutputQuantities(final Entity technology); }### Answer:
@Test public void shouldOmmitCheckingIfTheTreeIsntCompleteYet() { EntityTree tree = mockEntityTreeIterator(new LinkedList<Entity>()); given(technology.getTreeField("operationComponents")).willReturn(tree); List<String> messages = normService.checkOperationOutputQuantities(technology); assertTrue(messages.isEmpty()); }
@Test public void shouldNotFreakOutIfItCantFindOutputProductForAnOperationComponent() { EntityTree tree = mockEntityTreeIterator(asList(operComp1)); given(technology.getTreeField("operationComponents")).willReturn(tree); given(technologyService.getProductCountForOperationComponent(operComp1)).willThrow(new IllegalStateException()); List<String> messages = normService.checkOperationOutputQuantities(technology); assertTrue(messages.isEmpty()); }
@Ignore @Test public void shouldReturnAnErrorMessageIfTheQuantitiesDontMatch() { EntityTree tree = mockEntityTreeIterator(asList(operComp1)); given(technology.getTreeField("operationComponents")).willReturn(tree); given(technologyService.getProductCountForOperationComponent(operComp1)).willReturn(new BigDecimal(13.5)); given(operComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(13.51)); Locale locale = LocaleContextHolder.getLocale(); given(translationService.translate("technologies.technology.validate.error.invalidQuantity1", locale)).willReturn( "message1"); given(operComp1.getStringField("nodeNumber")).willReturn("1"); given(translationService.translate("technologies.technology.validate.error.invalidQuantity2", locale)).willReturn( "message2"); List<String> messages = normService.checkOperationOutputQuantities(technology); assertEquals(1, messages.size()); assertEquals("message1 1 message2", messages.get(0)); }
@Ignore @Test public void shouldReturnNoErrorsIfTheQuantitiesDoMatch() { EntityTree tree = mockEntityTreeIterator(asList(operComp1)); given(technology.getTreeField("operationComponents")).willReturn(tree); given(technologyService.getProductCountForOperationComponent(operComp1)).willReturn(new BigDecimal(13.5)); given(operComp1.getDecimalField("productionInOneCycle")).willReturn(new BigDecimal(13.500)); List<String> messages = normService.checkOperationOutputQuantities(technology); assertEquals(0, messages.size()); } |
### Question:
OrderDetailsHooksMR { public void setInputProductsRequiredForTypeFromParameters(final ViewDefinitionState view) { FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM); if (orderForm.getEntityId() != null) { return; } FieldComponent inputProductsRequiredForTypeField = (FieldComponent) view .getComponentByReference(OrderFieldsMR.INPUT_PRODUCTS_REQUIRED_FOR_TYPE); String inputProductsRequiredForType = (String) inputProductsRequiredForTypeField.getFieldValue(); if (StringUtils.isEmpty(inputProductsRequiredForType)) { inputProductsRequiredForTypeField.setFieldValue(getInputProductsRequiredForType()); } inputProductsRequiredForTypeField.requestComponentUpdateState(); } void setInputProductsRequiredForTypeFromParameters(final ViewDefinitionState view); }### Answer:
@Test public final void shouldSetInputProductsRequiredForTypeFromParameters() { given(inputProductsRequiredForTypeField.getFieldValue()).willReturn(null); orderDetailsHooksMR.setInputProductsRequiredForTypeFromParameters(view); verify(inputProductsRequiredForTypeField).setFieldValue(InputProductsRequiredForType.START_ORDER.getStringValue()); }
@Test public final void shouldntSetInputProductsRequiredForTypeFromParameters() { given(inputProductsRequiredForTypeField.getFieldValue()).willReturn( InputProductsRequiredForType.START_ORDER.getStringValue()); orderDetailsHooksMR.setInputProductsRequiredForTypeFromParameters(view); verify(inputProductsRequiredForTypeField, never()).setFieldValue( InputProductsRequiredForType.START_ORDER.getStringValue()); } |
### Question:
SamplesLoaderResolver { public SamplesLoader resolve() { final SamplesDataset samplesDataset = multiTenantService.getTenantSamplesDataset(); switch (samplesDataset) { case MINIMAL: return minimalSamplesLoader; case TEST: return testSamplesLoader; case GENERATED: return generatedSamplesLoader; case NONE: return dummySamplesLoader; default: throw new IllegalArgumentException("Unsupported dataset: " + samplesDataset); } } SamplesLoader resolve(); }### Answer:
@Test public final void shouldReturnMinimalSamplesLoader() throws Exception { given(multiTenantService.getTenantSamplesDataset()).willReturn(SamplesDataset.MINIMAL); SamplesLoader samplesLoader = samplesLoaderResolver.resolve(); assertEquals(minimalSamplesLoader, samplesLoader); }
@Test public final void shouldReturnTestSamplesLoader() throws Exception { given(multiTenantService.getTenantSamplesDataset()).willReturn(SamplesDataset.TEST); SamplesLoader samplesLoader = samplesLoaderResolver.resolve(); assertEquals(testSamplesLoader, samplesLoader); }
@Test public final void shouldReturnGeneratedSamplesLoader() throws Exception { given(multiTenantService.getTenantSamplesDataset()).willReturn(SamplesDataset.GENERATED); SamplesLoader samplesLoader = samplesLoaderResolver.resolve(); assertEquals(generatedSamplesLoader, samplesLoader); }
@Test public final void shouldReturnDummySamplesLoader() throws Exception { given(multiTenantService.getTenantSamplesDataset()).willReturn(SamplesDataset.NONE); SamplesLoader samplesLoader = samplesLoaderResolver.resolve(); assertEquals(dummySamplesLoader, samplesLoader); } |
### Question:
DeliveryDetailsListeners { public final void printDeliveryReport(final ViewDefinitionState view, final ComponentState state, final String[] args) { if (state instanceof FormComponent) { state.performEvent(view, "save", args); if (!state.isHasError()) { view.redirectTo("/deliveries/deliveryReport." + args[0] + "?id=" + state.getFieldValue(), true, false); } } else { state.addMessage("deliveries.delivery.report.componentFormError", MessageType.FAILURE); } } void fillCompanyFieldsForSupplier(final ViewDefinitionState view, final ComponentState state, final String[] args); final void printDeliveryReport(final ViewDefinitionState view, final ComponentState state, final String[] args); final void printOrderReport(final ViewDefinitionState view, final ComponentState state, final String[] args); final void copyProductsWithoutQuantityAndPrice(final ViewDefinitionState view, final ComponentState state,
final String[] args); final void copyProductsWithQuantityAndPrice(final ViewDefinitionState view, final ComponentState state,
final String[] args); final void recalculateReservations(final ViewDefinitionState view, final ComponentState state, final String[] args); final void changeStorageLocations(final ViewDefinitionState view, final ComponentState state, final String[] args); final void assignStorageLocations(final ViewDefinitionState view, final ComponentState state, final String[] args); final void createRelatedDelivery(final ViewDefinitionState view, final ComponentState state, final String[] args); BigDecimal getConversion(Entity product); final void showRelatedDeliveries(final ViewDefinitionState view, final ComponentState state, final String[] args); final void showProduct(final ViewDefinitionState view, final ComponentState state, final String[] args); void disableShowProductButton(final ViewDefinitionState view, final ComponentState state, final String[] args); void updateChangeStorageLocationButton(final ViewDefinitionState view, final ComponentState state, final String[] args); void validateColumnsWidthForOrder(final ViewDefinitionState view, final ComponentState state, final String[] args); void validateColumnsWidthForDelivery(final ViewDefinitionState view, final ComponentState state, final String[] args); void downloadAtachment(final ViewDefinitionState view, final ComponentState state, final String[] args); static final String OFFER; }### Answer:
@Test public void shouldRedirectToDeliveryReportOnPrintDelivery() throws Exception { String stateValue = "111"; when(formComponent.getFieldValue()).thenReturn(stateValue); deliveryDetailsListeners.printDeliveryReport(view, formComponent, args); verify(view).redirectTo("/deliveries/deliveryReport." + args[0] + "?id=" + stateValue, true, false); }
@Test public void shouldAddMessageWhenStateIsNotFormComponentOnPrintDelivery() throws Exception { String stateValue = "111"; when(grid.getFieldValue()).thenReturn(stateValue); deliveryDetailsListeners.printDeliveryReport(view, grid, args); verify(grid).addMessage("deliveries.delivery.report.componentFormError", MessageType.FAILURE); verify(view, never()).redirectTo("/deliveries/deliveryReport." + args[0] + "?id=" + stateValue, true, false); } |
### Question:
DeliveryDetailsListeners { public final void printOrderReport(final ViewDefinitionState view, final ComponentState state, final String[] args) { if (state instanceof FormComponent) { state.performEvent(view, "save", args); if (!state.isHasError()) { view.redirectTo("/deliveries/orderReport." + args[0] + "?id=" + state.getFieldValue(), true, false); } } else { state.addMessage("deliveries.order.report.componentFormError", MessageType.FAILURE); } } void fillCompanyFieldsForSupplier(final ViewDefinitionState view, final ComponentState state, final String[] args); final void printDeliveryReport(final ViewDefinitionState view, final ComponentState state, final String[] args); final void printOrderReport(final ViewDefinitionState view, final ComponentState state, final String[] args); final void copyProductsWithoutQuantityAndPrice(final ViewDefinitionState view, final ComponentState state,
final String[] args); final void copyProductsWithQuantityAndPrice(final ViewDefinitionState view, final ComponentState state,
final String[] args); final void recalculateReservations(final ViewDefinitionState view, final ComponentState state, final String[] args); final void changeStorageLocations(final ViewDefinitionState view, final ComponentState state, final String[] args); final void assignStorageLocations(final ViewDefinitionState view, final ComponentState state, final String[] args); final void createRelatedDelivery(final ViewDefinitionState view, final ComponentState state, final String[] args); BigDecimal getConversion(Entity product); final void showRelatedDeliveries(final ViewDefinitionState view, final ComponentState state, final String[] args); final void showProduct(final ViewDefinitionState view, final ComponentState state, final String[] args); void disableShowProductButton(final ViewDefinitionState view, final ComponentState state, final String[] args); void updateChangeStorageLocationButton(final ViewDefinitionState view, final ComponentState state, final String[] args); void validateColumnsWidthForOrder(final ViewDefinitionState view, final ComponentState state, final String[] args); void validateColumnsWidthForDelivery(final ViewDefinitionState view, final ComponentState state, final String[] args); void downloadAtachment(final ViewDefinitionState view, final ComponentState state, final String[] args); static final String OFFER; }### Answer:
@Test public void shouldRedirectToDeliveryReportOnPrintOrder() throws Exception { String stateValue = "111"; when(formComponent.getFieldValue()).thenReturn(stateValue); deliveryDetailsListeners.printOrderReport(view, formComponent, args); verify(view).redirectTo("/deliveries/orderReport." + args[0] + "?id=" + stateValue, true, false); }
@Test public void shouldAddMessageWhenStateIsNotFormComponentOnPrintOrder() throws Exception { String stateValue = "111"; when(grid.getFieldValue()).thenReturn(stateValue); deliveryDetailsListeners.printOrderReport(view, grid, args); verify(grid).addMessage("deliveries.order.report.componentFormError", MessageType.FAILURE); verify(view, never()).redirectTo("/deliveries/orderReport." + args[0] + "?id=" + stateValue, true, false); } |
### Question:
DeliveriesColumnLoader { public void addColumnsForDeliveries() { if (!deliveriesColumnLoaderService.isColumnsForDeliveriesEmpty()) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForDeliveries(DeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveries(); void deleteColumnsForDeliveries(); void addColumnsForOrders(); void deleteColumnsForOrders(); }### Answer:
@Test public void shouldAddColumnsForDeliveries() { given(deliveriesColumnLoaderService.isColumnsForDeliveriesEmpty()).willReturn(true); deliveriesColumnLoader.addColumnsForDeliveries(); verify(deliveriesColumnLoaderService).fillColumnsForDeliveries(Mockito.anyString()); }
@Test public void shouldntAddColumnsForDeliveries() { given(deliveriesColumnLoaderService.isColumnsForDeliveriesEmpty()).willReturn(false); deliveriesColumnLoader.addColumnsForDeliveries(); verify(deliveriesColumnLoaderService, never()).fillColumnsForDeliveries(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoader { public void deleteColumnsForDeliveries() { if (deliveriesColumnLoaderService.isColumnsForDeliveriesEmpty()) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Columns for deliveries table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForDeliveries(DeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveries(); void deleteColumnsForDeliveries(); void addColumnsForOrders(); void deleteColumnsForOrders(); }### Answer:
@Test public void shouldDeleteColumnsForDeliveries() { given(deliveriesColumnLoaderService.isColumnsForDeliveriesEmpty()).willReturn(false); deliveriesColumnLoader.deleteColumnsForDeliveries(); verify(deliveriesColumnLoaderService).clearColumnsForDeliveries(Mockito.anyString()); }
@Test public void shouldntDeleteColumnsForDeliveries() { given(deliveriesColumnLoaderService.isColumnsForDeliveriesEmpty()).willReturn(true); deliveriesColumnLoader.deleteColumnsForDeliveries(); verify(deliveriesColumnLoaderService, never()).clearColumnsForDeliveries(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoader { public void addColumnsForOrders() { if (!deliveriesColumnLoaderService.isColumnsForOrdersEmpty()) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be populated ..."); } deliveriesColumnLoaderService.fillColumnsForOrders(DeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveries(); void deleteColumnsForDeliveries(); void addColumnsForOrders(); void deleteColumnsForOrders(); }### Answer:
@Test public void shouldAddColumnsForOrders() { given(deliveriesColumnLoaderService.isColumnsForOrdersEmpty()).willReturn(true); deliveriesColumnLoader.addColumnsForOrders(); verify(deliveriesColumnLoaderService).fillColumnsForOrders(Mockito.anyString()); }
@Test public void shouldntAddColumnsForOrders() { given(deliveriesColumnLoaderService.isColumnsForOrdersEmpty()).willReturn(false); deliveriesColumnLoader.addColumnsForOrders(); verify(deliveriesColumnLoaderService, never()).fillColumnsForOrders(Mockito.anyString()); } |
### Question:
DeliveriesColumnLoader { public void deleteColumnsForOrders() { if (deliveriesColumnLoaderService.isColumnsForOrdersEmpty()) { return; } if (LOG.isDebugEnabled()) { LOG.debug("Columns for orders table will be unpopulated ..."); } deliveriesColumnLoaderService.clearColumnsForOrders(DeliveriesConstants.PLUGIN_IDENTIFIER); } void addColumnsForDeliveries(); void deleteColumnsForDeliveries(); void addColumnsForOrders(); void deleteColumnsForOrders(); }### Answer:
@Test public void shouldDeleteColumnsForOrders() { given(deliveriesColumnLoaderService.isColumnsForOrdersEmpty()).willReturn(false); deliveriesColumnLoader.deleteColumnsForOrders(); verify(deliveriesColumnLoaderService).clearColumnsForOrders(Mockito.anyString()); }
@Test public void shoulntdDeleteColumnsForOrders() { given(deliveriesColumnLoaderService.isColumnsForOrdersEmpty()).willReturn(true); deliveriesColumnLoader.deleteColumnsForOrders(); verify(deliveriesColumnLoaderService, never()).clearColumnsForOrders(Mockito.anyString()); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.