WorldpayItemCodePrepareInterceptor implements PrepareInterceptor<ItemModel> { @Override public void onPrepare(final ItemModel itemModel, final InterceptorContext interceptorContext) { final ComposedTypeModel type = typeService.getComposedTypeForCode(itemModel.getItemtype()); if (typeService.hasAttribute(type, fieldName)) { final ModelService modelService = interceptorContext.getModelService(); if (modelService.getAttributeValue(itemModel, fieldName) == null) { modelService.setAttributeValue(itemModel, fieldName, keyGenerator.generate()); } } }  @Override void onPrepare(final ItemModel itemModel, final InterceptorContext interceptorContext); @Required void setKeyGenerator(final KeyGenerator keyGenerator); @Required void setTypeService(final TypeService typeService); @Required void setFieldName(final String fieldName);  }
@Test public void onPrepareShouldSetKeyIfItemHasFieldName() throws InterceptorException { when(itemModelMock.getItemtype()).thenReturn(TYPE); when(typeServiceMock.getComposedTypeForCode(TYPE)).thenReturn(composedTypeModelMock); when(typeServiceMock.hasAttribute(composedTypeModelMock, FIELD_NAME)).thenReturn(true); when(interceptorContextMock.getModelService()).thenReturn(modelServiceMock); when(modelServiceMock.getAttributeValue(itemModelMock, FIELD_NAME)).thenReturn(null); when(keyGeneratorMock.generate()).thenReturn(GENERATED_KEY); testObj.onPrepare(itemModelMock, interceptorContextMock); verify(modelServiceMock).setAttributeValue(itemModelMock, FIELD_NAME, GENERATED_KEY); }
@Test public void onPrepareShouldNotSetKeyIfItemDoesNotHaveFieldName() throws InterceptorException { when(itemModelMock.getItemtype()).thenReturn(TYPE); when(typeServiceMock.getComposedTypeForCode(TYPE)).thenReturn(composedTypeModelMock); testObj.onPrepare(itemModelMock, interceptorContextMock); verify(modelServiceMock, never()).setAttributeValue(eq(itemModelMock), anyString(), anyString()); }
@Test public void onPrepareShouldNotSetKeyIfItemHasFieldAlreadySet() throws InterceptorException { when(itemModelMock.getItemtype()).thenReturn(TYPE); when(typeServiceMock.getComposedTypeForCode(TYPE)).thenReturn(composedTypeModelMock); when(typeServiceMock.hasAttribute(composedTypeModelMock, FIELD_NAME)).thenReturn(true); when(interceptorContextMock.getModelService()).thenReturn(modelServiceMock); when(modelServiceMock.getAttributeValue(itemModelMock, FIELD_NAME)).thenReturn(GENERATED_KEY); testObj.onPrepare(itemModelMock, interceptorContextMock); verify(modelServiceMock, never()).setAttributeValue(eq(itemModelMock), anyString(), anyString()); }