input
stringlengths 57
101k
| output
stringlengths 89
81.8k
⌀ | instruction
stringclasses 3
values |
---|---|---|
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ProcessingStatusServiceImpl implements ProcessingStatusService{
private final DossierDataService dossierDataService;
@Override
public void saveProcessingStatus(String movementId, String status) {
dossierDataService.saveProcessingStatus(createProcessingStatus(movementId, status));
}
private ProcessingStatus createProcessingStatus(String movementId, String status) {
ProcessingStatus processingStatus = new ProcessingStatus();
processingStatus.setStatus(status);
processingStatus.setMovementId(movementId);
return processingStatus;
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.mockito.Mockito.verify;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ProcessingStatusServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus;
import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ProcessingStatusServiceUT {
private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID";
@Mock
private DossierDataService dossierDataService;
@InjectMocks
private ProcessingStatusServiceImpl processingStatusService;
@Captor
private ArgumentCaptor<ProcessingStatus> processingStatusArgumentCaptor;
@Test
@DisplayName("Test - Save Processing Status")
void testSaveProcessingStatus() {
// Call ProcessingStatusService method:
processingStatusService.saveProcessingStatus(MOVEMENT_ID, ProcessingStatusTypeEnum.CARGO_OODEST_WRITTEN_OFF.getItemCode());
// Verification & Assertions:
verify(dossierDataService).saveProcessingStatus(processingStatusArgumentCaptor.capture());
assertEquals(MOVEMENT_ID, processingStatusArgumentCaptor.getValue().getMovementId());
assertEquals(ProcessingStatusTypeEnum.CARGO_OODEST_WRITTEN_OFF.getItemCode(), processingStatusArgumentCaptor.getValue().getStatus());
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.officeofdeparture.service;
import com.intrasoft.ermis.common.json.parsing.JsonConverter;
import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.ddntav5152.messages.PostponeEnquiryEvent;
import com.intrasoft.ermis.transit.bpmnshared.BpmnManagementService;
import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum;
import com.intrasoft.ermis.transit.officeofdeparture.domain.Message;
import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement;
import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum;
import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowVariablesEnum;
import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnTimersEnum;
import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.ProcessDefinitionEnum;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.xml.bind.JAXBException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class CustomsOfficerActionServiceImpl implements CustomsOfficerActionService {
private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter();
private final ErmisLogger log;
private final BpmnFlowService bpmnFlowService;
private final BpmnManagementService bpmnManagementService;
private final ProcessingStatusService processingStatusService;
private final GuaranteeService guaranteeService;
private final RecoveryService recoveryService;
private final DossierDataService dossierDataService;
private final PostReleaseTransitService postReleaseTransitService;
private final AmendmentRequestService amendmentRequestService;
private static final String FALLBACK_ACTIVITY_ID = "Gateway_Fallback";
private static final String CANCELLED_ACTIVITY_ID = "Gateway_0rylnq0";
@Override
public void handleRecommendEnquiryAction(Movement movement) {
if (ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode().equals(movement.getProcessingStatus())) {
bpmnFlowService.correlateMessage(movement.getMrn(), BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITHOUT_006.getTypeValue());
} else if (ProcessingStatusTypeEnum.OODEP_ARRIVED.getItemCode().equals(movement.getProcessingStatus())) {
bpmnFlowService.correlateMessage(movement.getMrn(), BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITH_006.getTypeValue());
}
}
@Override
public void handlePostponeEnquiryAction(Movement movement, String messageId) throws JAXBException {
Message postponeEnquiryMessage = dossierDataService.getMessageById(messageId);
PostponeEnquiryEvent postponeEnquiryEvent = JSON_CONVERTER.convertStringToObject(postponeEnquiryMessage.getPayload(), PostponeEnquiryEvent.class);
String formattedExpectedArrivalDate = Objects.nonNull(postponeEnquiryEvent.getExpectedArrivalDate()) ?
"P" + ChronoUnit.DAYS.between(LocalDate.now(ZoneOffset.UTC), postponeEnquiryEvent.getExpectedArrivalDate()) + "D" :
null;
String formattedExpectedControlDate = Objects.nonNull(postponeEnquiryEvent.getExpectedControlDate()) ?
"P" + ChronoUnit.DAYS.between(LocalDate.now(ZoneOffset.UTC), postponeEnquiryEvent.getExpectedControlDate()) + "D" :
null;
if (formattedExpectedArrivalDate != null) {
amendmentRequestService.updateLimitDate(movement.getId(), postponeEnquiryEvent.getExpectedControlDate());
processingStatusService.saveProcessingStatus(movement.getId(), ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode());
log.info("Going to stop 'Time To Enquire Timer'");
postReleaseTransitService.stopTimeToEnquireHolderTimerIfActive(movement.getMrn());
boolean isTimerActive = bpmnManagementService.isTimerActive(
movement.getMrn(),
ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(),
BpmnTimersEnum.AWAIT_RECEIPT_CONTROL_RESULTS.getActivityId());
if (isTimerActive) {
bpmnManagementService.modifyProcessInstance(
movement.getMrn(),
ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(),
FALLBACK_ACTIVITY_ID,
Map.of(BpmnFlowVariablesEnum.ARRIVAL_ADVICE_TIMER.getTypeValue(), formattedExpectedArrivalDate,
BpmnFlowVariablesEnum.IS_CONTROL_TIMER_ACTIVE.getTypeValue(), true,
BpmnFlowVariablesEnum.IS_EXPECTED_ARRIVAL_DATE_EMPTY.getTypeValue(), false,
BpmnFlowVariablesEnum.HAS_ENQUIRE_TIMER_STARTED.getTypeValue(), false),
List.of(CANCELLED_ACTIVITY_ID)
);
bpmnManagementService.changedDueDateOfTimer(
movement.getMrn(),
ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(),
BpmnTimersEnum.AWAIT_RECEIPT_CONTROL_RESULTS.getActivityId(),
formattedExpectedControlDate);
} else {
bpmnManagementService.modifyProcessInstance(
movement.getMrn(),
ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(),
FALLBACK_ACTIVITY_ID,
Map.of(BpmnFlowVariablesEnum.ARRIVAL_ADVICE_TIMER.getTypeValue(), formattedExpectedArrivalDate,
BpmnFlowVariablesEnum.RECEIPT_CONTROL_RESULTS_TIMER.getTypeValue(), Objects.requireNonNull(formattedExpectedControlDate),
BpmnFlowVariablesEnum.IS_CONTROL_TIMER_ACTIVE.getTypeValue(), false,
BpmnFlowVariablesEnum.IS_EXPECTED_ARRIVAL_DATE_EMPTY.getTypeValue(), false,
BpmnFlowVariablesEnum.HAS_ENQUIRE_TIMER_STARTED.getTypeValue(), false),
List.of(CANCELLED_ACTIVITY_ID)
);
}
} else {
processingStatusService.saveProcessingStatus(movement.getId(), ProcessingStatusTypeEnum.OODEP_ARRIVED.getItemCode());
log.info("Going to stop 'Time To Enquire Timer'");
postReleaseTransitService.stopTimeToEnquireHolderTimerIfActive(movement.getMrn());
bpmnManagementService.modifyProcessInstance(
movement.getMrn(),
ProcessDefinitionEnum.OODEPARTURE_RELEASE_TRANSIT_PROCESS.getProcessDefinitionKey(),
FALLBACK_ACTIVITY_ID,
Map.of(BpmnFlowVariablesEnum.RECEIPT_CONTROL_RESULTS_TIMER.getTypeValue(), Objects.requireNonNull(formattedExpectedControlDate),
BpmnFlowVariablesEnum.IS_EXPECTED_ARRIVAL_DATE_EMPTY.getTypeValue(), true,
BpmnFlowVariablesEnum.IS_CONTROL_TIMER_ACTIVE.getTypeValue(), false,
BpmnFlowVariablesEnum.HAS_ENQUIRE_TIMER_STARTED.getTypeValue(), false),
List.of(CANCELLED_ACTIVITY_ID)
);
}
}
@Override
public void handleGuaranteeIntegrityCheckAction(Movement movement, String messageId) {
guaranteeService.sendGuaranteeChecksToGMS(movement, messageId);
}
@Override
public void handleRecommendRecoveryAction(Movement movement) {
ProcessingStatusTypeEnum processingStatus = ProcessingStatusTypeEnum.findByItemCode(movement.getProcessingStatus());
switch (processingStatus) {
case OODEP_MOVEMENT_RELEASED:
bpmnFlowService.correlateMessageWithValues(movement.getMrn(), BpmnFlowMessagesEnum.MANUALLY_RECOMMEND_RECOVERY.getTypeValue(), Map.of(
BpmnFlowVariablesEnum.IS_RECOVERY_PROCEDURE_STARTED_BY_OFFICER.getTypeValue(), true));
break;
default:
recoveryService.startRecoveryForOfficerAction(movement.getId(), movement.getMrn());
break;
}
}
}
| package com.intrasoft.ermis.trs.officeofdeparture;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum;
import com.intrasoft.ermis.transit.officeofdeparture.domain.Movement;
import com.intrasoft.ermis.transit.officeofdeparture.domain.enums.BpmnFlowMessagesEnum;
import com.intrasoft.ermis.transit.officeofdeparture.service.BpmnFlowService;
import com.intrasoft.ermis.transit.officeofdeparture.service.CustomsOfficerActionServiceImpl;
import java.util.UUID;
import java.util.stream.Stream;
import org.junit.jupiter.api.Named;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class CustomOfficerActionServiceUT {
@Mock
private BpmnFlowService bpmnFlowService;
@InjectMocks
private CustomsOfficerActionServiceImpl customOfficerActionService;
@Captor
private ArgumentCaptor<String> messageNameArgumentCaptor;
@Captor
private ArgumentCaptor<String> businessKeyArgumentCaptor;
private static final String MRN = "TEST_MRN";
@ParameterizedTest
@MethodSource("namedArguments")
public void testHandlingOfRecommendEnquiryAction(String processingStatus) {
customOfficerActionService.handleRecommendEnquiryAction(createMovement(processingStatus));
if (ProcessingStatusTypeEnum.OODEP_NONE.getItemCode().equals(processingStatus)) {
verify(bpmnFlowService, times(0)).correlateMessage(any(), any());
} else {
verify(bpmnFlowService, times(1)).correlateMessage(businessKeyArgumentCaptor.capture(), messageNameArgumentCaptor.capture());
assertEquals(MRN, businessKeyArgumentCaptor.getValue());
if (ProcessingStatusTypeEnum.OODEP_ARRIVED.getItemCode().equals(processingStatus)) {
assertEquals(BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITH_006.getTypeValue(), messageNameArgumentCaptor.getValue());
} else if (ProcessingStatusTypeEnum.OODEP_MOVEMENT_RELEASED.getItemCode().equals(processingStatus)) {
assertEquals(BpmnFlowMessagesEnum.RECOMMEND_ENQUIRY_WITHOUT_006.getTypeValue(), messageNameArgumentCaptor.getValue());
}
}
}
static Stream<Arguments> namedArguments() {
return Stream.of(
Arguments.of(Named.of(" Arrived", "A01")),
Arguments.of(Named.of(" Movement Released", "A03")),
Arguments.of(Named.of(" None (not valid processing status)", "A0"))
);
}
private Movement createMovement(String processingStatus) {
return Movement.builder()
.id(UUID.randomUUID().toString())
.processingStatus(processingStatus)
.mrn(MRN)
.build();
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.officeofexitfortransit.core.service;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.ddntav5152.messages.CD165CType;
import com.intrasoft.ermis.transit.common.exceptions.BaseException;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class InspectionServiceImpl implements InspectionService {
private final DossierDataService dossierDataService;
@Override
public boolean isIE165Positive(String messageId) {
try {
Message message = dossierDataService.getMessageById(messageId);
CD165CType cd165cType = XmlConverter.buildMessageFromXML(message.getPayload(), CD165CType.class);
if (cd165cType.getTransitOperation().getRequestRejectionReasonCode() == null) {
return true;
} else {
return cd165cType.getTransitOperation().getRequestRejectionReasonCode().isEmpty();
}
} catch (Exception e) {
throw new BaseException("isIE165Positive(): ERROR!", e);
}
}
}
| package com.intrasoft.ermis.transit.officeofexitfortransit.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.xml.enums.NamespacesEnum;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.ddntav5152.messages.CD165CType;
import com.intrasoft.ermis.ddntav5152.messages.MessageTypes;
import com.intrasoft.ermis.ddntav5152.messages.TransitOperationType41;
import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.DossierDataService;
import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.InspectionServiceImpl;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class InspectionServiceUT {
@Mock
private DossierDataService dossierDataService;
@InjectMocks
private InspectionServiceImpl inquiryService;
@ParameterizedTest
@ValueSource(booleans = {true, false})
@DisplayName("Test - Is IE165 Positive")
void testIsIE165Positive(boolean requestRejectionCodeExists) {
System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true");
Message message = createMessage(requestRejectionCodeExists);
try {
// Mocks:
when(dossierDataService.getMessageById(any())).thenReturn(message);
// Call InspectionService method:
boolean expectedResult = inquiryService.isIE165Positive(UUID.randomUUID().toString());
// Assertion:
assertEquals(expectedResult, !requestRejectionCodeExists);
} catch (Exception e) {
fail();
}
}
private Message createMessage(boolean requestRejectionCodeExists) {
CD165CType cd165cTypeMessage = new CD165CType();
cd165cTypeMessage.setTransitOperation(new TransitOperationType41());
if (requestRejectionCodeExists) {
cd165cTypeMessage.getTransitOperation().setRequestRejectionReasonCode("TEST");
}
Message message = new Message();
message.setPayload(XmlConverter.marshal(cd165cTypeMessage, NamespacesEnum.NTA.getValue(), MessageTypes.CD_165_C.value()));
return message;
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.MessageOverview;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult;
import com.intrasoft.ermis.transit.common.exceptions.NotFoundException;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.MessageOverviewDTO;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.PaginatedDTO;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierDeclarationPort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMessagePort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMovementPort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierProcessingStatusPort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierValidationResultsPort;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class DossierDataServiceImpl implements DossierDataService {
// Ports:
private final DossierMovementPort dossierMovementPort;
private final DossierMessagePort dossierMessagePort;
private final DossierProcessingStatusPort dossierProcessingStatusPort;
private final DossierDeclarationPort dossierDeclarationPort;
private final DossierValidationResultsPort dossierValidationResultsPort;
// Mappers:
private final MovementDTOMapper movementDTOMapper;
private final MessageDTOMapper messageDTOMapper;
private final MessageOverviewDTOMapper messageOverviewDTOMapper;
private final ProcessingStatusDTOMapper processingStatusDTOMapper;
private final DeclarationDTOMapper declarationDTOMapper;
private final ValidationResultDTOMapper validationResultDTOMapper;
@Override
public Movement getMovementById(String movementId) {
return movementDTOMapper.toDomain(dossierMovementPort.findById(movementId, false).getBody());
}
@Override
public Movement updateMovement(Movement movement) {
return movementDTOMapper.toDomain(dossierMovementPort.update(movementDTOMapper.toDTO(movement), movement.getId()).getBody());
}
@Override
public List<MessageOverview> getMessageOverviewList(String movementId, String messageType, Boolean isRejected) {
PaginatedDTO<MessageOverviewDTO> messageOverviewDTOListBody =
dossierMessagePort.findOverviewByCriteria(movementId, messageType, null, isRejected, null, null, 0, 20, false).getBody();
if (messageOverviewDTOListBody != null) {
return messageOverviewDTOMapper.toDomain(messageOverviewDTOListBody.getContent());
} else {
log.error("Message Overview list body was NULL, returning empty list.");
return new ArrayList<>();
}
}
@Override
public Message saveMessage(Message message) {
return messageDTOMapper.toDomain(dossierMessagePort.add(messageDTOMapper.toDTO(message)).getBody());
}
@Override
public Message getMessageById(String messageId) {
return messageDTOMapper.toDomain(dossierMessagePort.findById(messageId, false, false, false).getBody());
}
@Override
public void associateMessageWithMovement(String messageId, String movementId) {
dossierMessagePort.associateMovement(messageId, movementId);
}
@Override
public Message updateMessageStatus(String id, String status) {
return messageDTOMapper.toDomain(dossierMessagePort.update(id, status).getBody());
}
@Override
public void saveProcessingStatus(ProcessingStatus processingStatus) {
dossierProcessingStatusPort.add(processingStatusDTOMapper.toDTO(processingStatus));
}
@Override
public void createDeclaration(Declaration declaration) {
dossierDeclarationPort.add(declarationDTOMapper.toDTO(declaration));
}
@Override
public Declaration getLatestDeclarationByMovementId(String movementId) {
try {
return declarationDTOMapper.toDomain(dossierDeclarationPort.findCurrentVersionByMovementId(movementId, false, false).getBody());
} catch (NotFoundException e) {
return null;
}
}
@Override
public void saveValidationResultList(List<ValidationResult> validationResultList) {
dossierValidationResultsPort.saveValidationResults(validationResultDTOMapper.toDTO(validationResultList));
}
@Override
public List<ValidationResult> findValidationResultListByMessageId(String messageId) {
return validationResultDTOMapper.toDomain(dossierValidationResultsPort.findValidationResultsByMessageId(messageId).getBody());
}
@Override
public boolean mrnExists(String mrn) {
return Boolean.TRUE.equals(dossierMovementPort.existsByCriteria(mrn, null, null, null).getBody());
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.cargov1.messages.MessageTypes;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.DeclarationDTOMapperImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageDTOMapperImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MessageOverviewDTOMapperImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.MovementDTOMapperImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ProcessingStatusDTOMapperImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapper;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.mapper.ValidationResultDTOMapperImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service.DossierDataServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ProcessingStatus;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult;
import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.DeclarationDTO;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.MessageDTO;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.MovementDTO;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.PaginatedDTO;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.ProcessingStatusDTO;
import com.intrasoft.ermis.platform.contracts.dossier.dtos.ValidationResultDTO;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierDeclarationPort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMessagePort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierMovementPort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierProcessingStatusPort;
import com.intrasoft.ermis.transit.shared.dossier.clients.DossierValidationResultsPort;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
@ExtendWith(MockitoExtension.class)
class DossierDataServiceUT {
private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID";
private static final String MESSAGE_ID = "TEST_MESSAGE_ID";
private static final String MESSAGE_IDENTIFICATION = "TEST_MESSAGE_IDENTIFICATION";
private static final String MRN = "TEST_MRN";
@Mock
private DossierMovementPort dossierMovementPort;
@Mock
private DossierMessagePort dossierMessagePort;
@Mock
private DossierProcessingStatusPort dossierProcessingStatusPort;
@Mock
private DossierDeclarationPort dossierDeclarationPort;
@Mock
private DossierValidationResultsPort dossierValidationResultsPort;
@Spy
private MovementDTOMapper movementDTOMapper = new MovementDTOMapperImpl();
@Spy
private MessageDTOMapper messageDTOMapper = new MessageDTOMapperImpl();
@Spy
private MessageOverviewDTOMapper messageOverviewDTOMapper = new MessageOverviewDTOMapperImpl();
@Spy
private ProcessingStatusDTOMapper processingStatusDTOMapper = new ProcessingStatusDTOMapperImpl();
@Spy
private DeclarationDTOMapper declarationDTOMapper = new DeclarationDTOMapperImpl();
@Spy
private ValidationResultDTOMapper validationResultDTOMapper = new ValidationResultDTOMapperImpl();
@InjectMocks
private DossierDataServiceImpl dossierDataService;
@Captor
private ArgumentCaptor<MovementDTO> movementDTOArgumentCaptor;
@Captor
private ArgumentCaptor<ProcessingStatusDTO> processingStatusDTOArgumentCaptor;
@Captor
private ArgumentCaptor<DeclarationDTO> declarationDTOArgumentCaptor;
@Captor
private ArgumentCaptor<MessageDTO> messageDTOArgumentCaptor;
@Captor
private ArgumentCaptor<List<ValidationResultDTO>> validationResultDTOListArgumentCaptor;
@Captor
private ArgumentCaptor<String> messageIdCaptor;
@Captor
private ArgumentCaptor<String> statusCaptor;
@Test
@DisplayName("Test - Get Movement by ID")
void testGetMovementById() {
// Stub:
when(dossierMovementPort.findById(MOVEMENT_ID, false)).thenReturn(ResponseEntity.ok(new MovementDTO()));
// Call DossierDataService method:
dossierDataService.getMovementById(MOVEMENT_ID);
// Verification:
verify(dossierMovementPort, times(1)).findById(MOVEMENT_ID, false);
}
@Test
@DisplayName("Test - Update Movement")
void testUpdateMovement() {
Movement testMovement = Movement.builder().id(MOVEMENT_ID).build();
// Stub:
when(dossierMovementPort.update(any(), eq(MOVEMENT_ID))).thenReturn(ResponseEntity.ok(new MovementDTO()));
// Call DossierDataService method:
dossierDataService.updateMovement(testMovement);
// Verification & Assertion:
verify(dossierMovementPort, times(1)).update(movementDTOArgumentCaptor.capture(), eq(MOVEMENT_ID));
assertEquals(MOVEMENT_ID, movementDTOArgumentCaptor.getValue().getId());
}
@Test
@DisplayName("Test - Get Message Overview List")
void testGetMessageOverviewList() {
// Stub:
when(dossierMessagePort.findOverviewByCriteria(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null,
null, null, null, 0, 20, false)).thenReturn(ResponseEntity.ok(new PaginatedDTO<>()));
// Call DossierDataService method:
dossierDataService.getMessageOverviewList(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null);
// Verification:
verify(dossierMessagePort, times(1)).findOverviewByCriteria(MOVEMENT_ID, MessageTypes.TB_015_C.value(), null,
null, null, null, 0, 20, false);
}
@Test
@DisplayName("Test - Save Message")
void testSaveMessage() {
Message testMessage = Message.builder().messageIdentification(MESSAGE_IDENTIFICATION).build();
// Stub:
when(dossierMessagePort.add(any(MessageDTO.class))).thenReturn(ResponseEntity.ok(new MessageDTO()));
// Call DossierDataService method:
dossierDataService.saveMessage(testMessage);
// Verification & Assertion:
verify(dossierMessagePort, times(1)).add(messageDTOArgumentCaptor.capture());
assertEquals(MESSAGE_IDENTIFICATION, messageDTOArgumentCaptor.getValue().getMessageIdentification());
}
@Test
@DisplayName("Test - Get Message by ID")
void testGetMessageById() {
// Stub:
when(dossierMessagePort.findById(MESSAGE_ID, false, false, false)).thenReturn(ResponseEntity.ok(new MessageDTO()));
// Call DossierDataService method:
dossierDataService.getMessageById(MESSAGE_ID);
// Verification:
verify(dossierMessagePort, times(1)).findById(MESSAGE_ID, false, false, false);
}
@Test
@DisplayName("Test - Associate Message with Movement")
void testAssociateMessageWithMovement() {
// Stub:
when(dossierMessagePort.associateMovement(MESSAGE_ID, MOVEMENT_ID)).thenReturn(ResponseEntity.ok(null));
// Call DossierDataService method:
dossierDataService.associateMessageWithMovement(MESSAGE_ID, MOVEMENT_ID);
// Verification:
verify(dossierMessagePort, times(1)).associateMovement(MESSAGE_ID, MOVEMENT_ID);
}
@Test
@DisplayName("Test - Update Message Status")
void testUpdateMessageStatus() {
// Stub:
when(dossierMessagePort.update(MESSAGE_ID, MessageStatusEnum.REJECTED.name())).thenReturn(ResponseEntity.ok(new MessageDTO()));
// Call DossierDataService method:
dossierDataService.updateMessageStatus(MESSAGE_ID, MessageStatusEnum.REJECTED.name());
// Verification:
verify(dossierMessagePort, times(1)).update(MESSAGE_ID, MessageStatusEnum.REJECTED.name());
}
@Test
@DisplayName("Test - Save Processing Status")
void testSaveProcessingStatus() {
ProcessingStatus testProcessingStatus = ProcessingStatus.builder()
.movementId(MOVEMENT_ID)
.status("TEST_STATUS")
.reasonType("TEST_REASON")
.build();
// Call DossierDataService method:
dossierDataService.saveProcessingStatus(testProcessingStatus);
// Verification & Assertions:
verify(dossierProcessingStatusPort, times(1)).add(processingStatusDTOArgumentCaptor.capture());
assertEquals(testProcessingStatus.getMovementId(), processingStatusDTOArgumentCaptor.getValue().getMovementId());
assertEquals(testProcessingStatus.getStatus(), processingStatusDTOArgumentCaptor.getValue().getStatus());
assertEquals(testProcessingStatus.getReasonType(), processingStatusDTOArgumentCaptor.getValue().getReasonType());
}
@Test
@DisplayName("Test - Create Declaration")
void testCreateDeclaration() {
Declaration testMovement = Declaration.builder().movementId(MOVEMENT_ID).build();
// Call DossierDataService method:
dossierDataService.createDeclaration(testMovement);
// Verification & Assertion:
verify(dossierDeclarationPort, times(1)).add(declarationDTOArgumentCaptor.capture());
assertEquals(MOVEMENT_ID, declarationDTOArgumentCaptor.getValue().getMovementId());
}
@Test
@DisplayName("Test - Get latest Declaration by Movement ID")
void testGetLatestDeclarationByMovementId() {
// Stub:
when(dossierDeclarationPort.findCurrentVersionByMovementId(MOVEMENT_ID, false, false)).thenReturn(ResponseEntity.ok(new DeclarationDTO()));
// Call DossierDataService method:
dossierDataService.getLatestDeclarationByMovementId(MOVEMENT_ID);
// Verification:
verify(dossierDeclarationPort, times(1)).findCurrentVersionByMovementId(MOVEMENT_ID, false, false);
}
@Test
@DisplayName("Test - Save Validation Result List")
void testSaveValidationResultList() {
List<ValidationResult> testValidationResultList = new ArrayList<>();
ValidationResult testValidationResult = new ValidationResult();
testValidationResult.setMessageId(MESSAGE_ID);
testValidationResultList.add(testValidationResult);
// Call DossierDataService method:
dossierDataService.saveValidationResultList(testValidationResultList);
// Verification & Assertion:
verify(dossierValidationResultsPort, times(1)).saveValidationResults(validationResultDTOListArgumentCaptor.capture());
assertEquals(MESSAGE_ID, validationResultDTOListArgumentCaptor.getValue().get(0).getMessageId());
}
@Test
@DisplayName("Test - Find Validation Result list by Message ID")
void testFindValidationResultListByMessageId() {
// Stub:
when(dossierValidationResultsPort.findValidationResultsByMessageId(MESSAGE_ID)).thenReturn(ResponseEntity.ok(new ArrayList<>()));
// Call DossierDataService method:
dossierDataService.findValidationResultListByMessageId(MESSAGE_ID);
// Verification:
verify(dossierValidationResultsPort, times(1)).findValidationResultsByMessageId(MESSAGE_ID);
}
@ParameterizedTest
@DisplayName("Test - MRN Exists")
@ValueSource(booleans = {true, false})
void testMRNExists(boolean mrnExists) {
// Stub:
when(dossierMovementPort.existsByCriteria(MRN, null, null, null))
.thenReturn(ResponseEntity.ok(mrnExists));
// Call DossierDataService method:
boolean returnedValue = dossierDataService.mrnExists(MRN);
// Verification & Assertion:
verify(dossierMovementPort, times(1)).existsByCriteria(MRN, null, null, null);
assertEquals(mrnExists, returnedValue);
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.management.core.service.report;
import static com.intrasoft.ermis.transit.management.core.service.report.ReportServiceImpl.VALID_NP_REPORT_MESSAGE_TYPES;
import static com.intrasoft.ermis.transit.management.core.service.report.ReportServiceImpl.VALID_TAD_REPORT_MESSAGE_TYPES;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.ddntav5152.messages.CC013CType;
import com.intrasoft.ermis.ddntav5152.messages.CC015CType;
import com.intrasoft.ermis.ddntav5152.messages.CC029CType;
import com.intrasoft.ermis.ddntav5152.messages.CD001CType;
import com.intrasoft.ermis.ddntav5152.messages.CD003CType;
import com.intrasoft.ermis.ddntav5152.messages.CD038CType;
import com.intrasoft.ermis.ddntav5152.messages.CD050CType;
import com.intrasoft.ermis.ddntav5152.messages.CD115CType;
import com.intrasoft.ermis.ddntav5152.messages.CD160CType;
import com.intrasoft.ermis.ddntav5152.messages.CD165CType;
import com.intrasoft.ermis.ddntav5152.messages.MessageTypes;
import com.intrasoft.ermis.transit.common.exceptions.BaseException;
import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper;
import com.intrasoft.ermis.transit.management.domain.Message;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
/**
* <pre>
* Generates a CC029C type message from a compatible DDNTA message type of one of the following types
* CC015C
* If the input message is already a CC029C type, then no conversion takes place
* The generated CC029C message will be fed to the existing TAD report generation implementation
*/
@Service
@RequiredArgsConstructor
public class ReportMessageTranslatorImpl implements ReportMessageTranslatorService{
private final MessageTypeMapper messageTypeMapper;
public Message generateCC029CTypeMessageFromOriginalMessage(Message originalMessage) {
MessageTypes originalMessageType = findMessageType(originalMessage);
if (originalMessageType == MessageTypes.CC_029_C) {
return originalMessage;
} else if (VALID_TAD_REPORT_MESSAGE_TYPES.contains(originalMessageType)) {
return mapToCC029C(originalMessage, originalMessageType);
} else {
throw new BaseException(String.format("IE message of type: '%s' is not valid for TAD generation", originalMessageType.value()));
}
}
public Message generateCC015CTypeMessageFromOriginalMessage(Message originalMessage) {
MessageTypes originalMessageType = findMessageType(originalMessage);
if (originalMessageType == MessageTypes.CC_015_C) {
return originalMessage;
} else if (VALID_NP_REPORT_MESSAGE_TYPES.contains(originalMessageType)) {
return mapToCC015C(originalMessage, originalMessageType);
} else {
throw new BaseException(String.format("IE message of type: '%s' is not valid for TAD generation", originalMessageType.value()));
}
}
public static MessageTypes findMessageType(Message message) {
String messageId = message.getId();
String messageType = message.getMessageType();
try {
return MessageTypes.fromValue(messageType);
} catch (IllegalArgumentException ex) {
throw new IllegalArgumentException(String.format("Unknown DDNTA message type: '%s' for IE message with id '%s'.", messageType, messageId), ex);
}
}
protected Message mapToCC029C(Message message, MessageTypes messageType) {
return generateCC029CMessage(message.getPayload(), generateDDNTAClassFromMessageType(messageType));
}
protected Message mapToCC015C(Message message, MessageTypes messageType) {
return generateCC015CMessage(message.getPayload(), generateDDNTAClassFromMessageType(messageType));
}
@SneakyThrows
protected <T> Message generateCC029CMessage(String xmlPayload, Class<T> clazz) {
T t = XmlConverter.buildMessageFromXML(xmlPayload, clazz);
return Message.builder().payload(
XmlConverter.marshal(
enhanceGeneratedCC029C(convertToCC029C(t))))
.messageType(MessageTypes.CC_029_C.value())
.build();
}
@SneakyThrows
protected <T> Message generateCC015CMessage(String xmlPayload, Class<T> clazz) {
T t = XmlConverter.buildMessageFromXML(xmlPayload, clazz);
return Message.builder().payload(
XmlConverter.marshal(
enhanceGeneratedCC015C(convertToCC015C(t))))
.messageType(MessageTypes.CC_015_C.value())
.build();
}
protected <T> CC029CType convertToCC029C(T t) {
CC029CType result;
var messageType = MessagTypesConvertibleToCC029CEnum.fromValue(t.getClass().getSimpleName());
switch (Objects.requireNonNull(messageType)) {
case CC015C:
result = messageTypeMapper.fromCC015CtoCC029C((CC015CType) t);
break;
case CD001C:
result = messageTypeMapper.fromCD001CToCC029C((CD001CType) t);
break;
case CD003C:
result = messageTypeMapper.fromCD003CToCC029C((CD003CType) t);
break;
case CD160C:
result = messageTypeMapper.fromCD160CToCC029C((CD160CType) t);
break;
case CD165C:
result = messageTypeMapper.fromCD165CToCC029C((CD165CType) t);
break;
case CD050C:
result = messageTypeMapper.fromCD050CToCC029C((CD050CType) t);
break;
case CD115C:
result = messageTypeMapper.fromCD115CToCC029C((CD115CType) t);
break;
case CD038C:
result = messageTypeMapper.fromCD038CToCC029C((CD038CType) t);
break;
default:
throw new BaseException("Invalid message Type Class: " + t.getClass().getSimpleName());
}
result.setMessageType(MessageTypes.CC_029_C);
return result;
}
protected <T> CC015CType convertToCC015C(T t) {
CC015CType result;
var messageType = MessageTypesConvertibleToCC013CEnum.fromValue(t.getClass().getSimpleName());
switch (Objects.requireNonNull(messageType)) {
case CC013C:
result = messageTypeMapper.fromCC013toCC015CType((CC013CType) t);
break;
default:
throw new BaseException("Invalid message Type Class: " + t.getClass().getSimpleName());
}
result.setMessageType(MessageTypes.CC_015_C);
return result;
}
/**
* Potentially enrich the generated CC029C with possible extra elements that are missing in the Original Documents and are needed in the TAD document.
* Nothing found till now though e.g. <combinedNomenclatureCode></combinedNomenclatureCode>
*/
private static CC029CType enhanceGeneratedCC029C(CC029CType cc029CType) {
return cc029CType;
}
private static CC015CType enhanceGeneratedCC015C(CC015CType cc015Type) {
return cc015Type;
}
@SneakyThrows
public static Class<?> generateDDNTAClassFromMessageType(MessageTypes messageType) {
return Class.forName(MessageTypes.class.getPackageName() + "." + messageType.value() + "Type");
}
@RequiredArgsConstructor
enum MessagTypesConvertibleToCC029CEnum {
CD001C(CD001CType.class.getSimpleName()),
CD003C(CD003CType.class.getSimpleName()),
CD160C(CD160CType.class.getSimpleName()),
CD165C(CD165CType.class.getSimpleName()),
CD050C(CD050CType.class.getSimpleName()),
CD115C(CD115CType.class.getSimpleName()),
CD038C(CD038CType.class.getSimpleName()),
CC015C(CC015CType.class.getSimpleName());
private final String classSimpleName;
public static MessagTypesConvertibleToCC029CEnum fromValue(String value) {
for (MessagTypesConvertibleToCC029CEnum e : values()) {
if (e.classSimpleName.equals(value)) {
return e;
}
}
return null;
}
}
@RequiredArgsConstructor
enum MessageTypesConvertibleToCC013CEnum {
CC013C(CC013CType.class.getSimpleName());
private final String classSimpleName;
public static MessageTypesConvertibleToCC013CEnum fromValue(String value) {
for (MessageTypesConvertibleToCC013CEnum e : values()) {
if (e.classSimpleName.equals(value)) {
return e;
}
}
return null;
}
}
}
| package com.intrasoft.ermis.transit.management.core.service;
import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper;
import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapperImpl;
import com.intrasoft.ermis.transit.management.core.service.report.ReportMessageTranslatorImpl;
import com.intrasoft.ermis.transit.management.domain.Message;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class ReportMessageTranslatorUT {
@Spy
private MessageTypeMapper messageTypeMapper = new MessageTypeMapperImpl();
@InjectMocks
private ReportMessageTranslatorImpl messageTranslator;
@Test
void testGenerateCC029CTypeMessageFromOriginalMessage() {
Message originalMessage = Message.builder()
.id("123")
.messageType("CC015C")
.payload("<xml>...</xml>")
.build();
Message resultMessage = messageTranslator.generateCC029CTypeMessageFromOriginalMessage(originalMessage);
assertNotNull(resultMessage);
assertEquals("CC029C", resultMessage.getMessageType());
}
@Test
void testGenerateCC029CTypeMessageFromOriginalMessageWhenAlreadyCC029C() {
// Test the case where input type is already CC029C
Message originalMessage = Message.builder()
.id("123")
.messageType("CC029C")
.payload("<xml>...</xml>")
.build();
Message resultMessage = messageTranslator.generateCC029CTypeMessageFromOriginalMessage(originalMessage);
assertNotNull(resultMessage);
assertEquals(originalMessage, resultMessage);
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ArrivalPresentationServiceImpl implements ArrivalPresentationService {
private final DossierDataService dossierDataService;
private static final String RULE_ID = "CARGO_ARRIVAL_PRESENTATION_TIMER_EXPIRATION";
private static final String ERROR_CODE = "N/A";
private static final String ERROR_POINTER = "/TB015C/preparationDateAndTime";
@Override
public void handleArrivalPresentationTimeout(String messageId) {
// Persist rejecting Validation Result due to Cargo Arrival Presentation timer expiration:
List<ValidationResult> validationResultList = new ArrayList<>();
ValidationResult rejectingValidationResult = ValidationResult.builder()
.messageId(messageId)
.createdDateTime(LocalDateTime.now(ZoneOffset.UTC))
.rejecting(true)
.ruleId(RULE_ID)
.errorCode(ERROR_CODE)
.pointer(ERROR_POINTER)
.build();
validationResultList.add(rejectingValidationResult);
dossierDataService.saveValidationResultList(validationResultList);
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.mockito.Mockito.verify;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ArrivalPresentationServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.ValidationResult;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ArrivalPresentationServiceUT {
private static final String MESSAGE_ID = "TEST_MESSAGE_ID";
private static final String RULE_ID = "CARGO_ARRIVAL_PRESENTATION_TIMER_EXPIRATION";
private static final String ERROR_CODE = "N/A";
private static final String ERROR_POINTER = "/TB015C/preparationDateAndTime";
@Mock
private DossierDataService dossierDataService;
@InjectMocks
private ArrivalPresentationServiceImpl arrivalPresentationService;
@Captor
private ArgumentCaptor<List<ValidationResult>> validationResultListArgumentCaptor;
@Test
@DisplayName("Test - Handle Arrival Presentation Timeout")
void testHandleArrivalPresentationTimeout() {
// Call ArrivalPresentationService method:
arrivalPresentationService.handleArrivalPresentationTimeout(MESSAGE_ID);
// Verification & Assertions:
verify(dossierDataService).saveValidationResultList(validationResultListArgumentCaptor.capture());
ValidationResult validationResultActual = validationResultListArgumentCaptor.getValue().get(0);
assertEquals(MESSAGE_ID, validationResultActual.getMessageId());
assertEquals(RULE_ID, validationResultActual.getRuleId());
assertEquals(ERROR_CODE, validationResultActual.getErrorCode());
assertEquals(ERROR_POINTER, validationResultActual.getPointer());
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.cargov1.messages.MessageTypes;
import com.intrasoft.ermis.cargov1.messages.TB015CType;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationArrivalNotificationFacade;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationInvalidationFacade;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationMainFacade;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import com.intrasoft.ermis.transit.common.exceptions.BaseException;
import com.intrasoft.ermis.transit.common.exceptions.NotFoundException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import javax.xml.bind.JAXBException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ProcessMessageServiceImpl implements ProcessMessageService {
private final ErmisLogger logger;
private final DossierDataService dossierDataService;
private final CargoOoDestinationMainFacade mainFacade;
private final CargoOoDestinationArrivalNotificationFacade arrivalNotificationFacade;
private final CargoOoDestinationInvalidationFacade invalidationFacade;
@Override
public void process(String messageId, String messageType, String movementId) {
try {
MessageTypes cargoMessageType = MessageTypes.fromValue(messageType);
switch (cargoMessageType) {
case TB_007_C:
handleTB007C(movementId, messageId);
break;
case TB_014_C:
handleTB014C(movementId, messageId);
break;
case TB_015_C:
handleTB015C(movementId, messageId);
break;
default:
logger.warn("Failed to process Message with type: {}, ignoring.", cargoMessageType.value());
break;
}
} catch (IllegalArgumentException exception) {
logger.error(String.format("process(): MESSAGE PROCESSING EXCEPTION -> messageType: [%s], messageId: [%s], movementId: [%s]",
messageType, messageId, movementId), exception);
}
}
private void handleTB007C(String movementId, String messageId) {
arrivalNotificationFacade.initProcessInstance(movementId, messageId);
}
private void handleTB014C(String movementId, String messageId) {
invalidationFacade.initProcessInstance(movementId, messageId);
}
private void handleTB015C(String movementId, String messageId) {
Movement movement = getMovement(movementId);
Message message = getMessage(messageId);
if (movement != null && message != null) {
// Create Declaration and update Movement:
createDeclaration(message, movementId);
updateMovementWithDeclarationDataFromMessage(movement, message);
mainFacade.initProcessInstance(movementId, messageId);
}
}
private Movement getMovement(String movementId) {
try {
return dossierDataService.getMovementById(movementId);
} catch (NotFoundException e) {
logger.info("No Movement with ID: {} was found.", movementId);
return null;
}
}
private Message getMessage(String messageId) {
try {
return dossierDataService.getMessageById(messageId);
} catch (NotFoundException e) {
logger.info("No Message with ID: {} was found.", messageId);
return null;
}
}
private void createDeclaration(Message message, String movementId) {
logger.info("Create Declaration for messageId: {} and movementId: {}", message.getId(), movementId);
Declaration declaration = Declaration.builder()
.movementId(movementId)
.payloadType(message.getMessageType())
.payload(message.getPayload())
.build();
dossierDataService.createDeclaration(declaration);
}
private void updateMovementWithDeclarationDataFromMessage(Movement movement, Message message) {
try {
TB015CType tb015cTypeMessage = XmlConverter.buildMessageFromXML(message.getPayload(), TB015CType.class);
movement.setDeclarationType(tb015cTypeMessage.getTransitOperation().getDeclarationType());
movement.setSubmitterIdentification(tb015cTypeMessage.getHolderOfTheTransitProcedure().getIdentificationNumber());
movement.setOfficeOfDeparture(tb015cTypeMessage.getCustomsOfficeOfDeparture().getReferenceNumber());
movement.setOfficeOfDestination(tb015cTypeMessage.getCustomsOfficeOfDestinationDeclared().getReferenceNumber());
movement.setCountryOfDestination(tb015cTypeMessage.getConsignment().getCountryOfDestination());
movement.setAcceptanceDateTime(LocalDateTime.now(ZoneOffset.UTC));
dossierDataService.updateMovement(movement);
} catch (JAXBException e) {
throw new BaseException("updateMovementWithDeclarationData(): ERROR during Message XML conversion.", e);
}
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.cargov1.messages.MessageTypes;
import com.intrasoft.ermis.cargov1.messages.TB015CType;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.common.xml.enums.NamespacesEnum;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationArrivalNotificationFacade;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationInvalidationFacade;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.process.CargoOoDestinationMainFacade;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ProcessMessageServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import com.intrasoft.ermis.transit.cargoofficeofdestination.test.util.TestDataUtilities;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ProcessMessageServiceUT {
private static final String MOVEMENT_ID_PREFIX = "MOVEMENT_ID_";
private static final String MESSAGE_ID_PREFIX = "MESSAGE_ID_";
private static final String TEST_DEPARTURE_OFFICE = "DK000000";
private static final String TEST_DESTINATION_OFFICE = "DK111111";
@Mock
private ErmisLogger logger;
@Mock
private DossierDataService dossierDataService;
@Mock
private CargoOoDestinationMainFacade mainFacade;
@Mock
private CargoOoDestinationArrivalNotificationFacade arrivalNotificationFacade;
@Mock
private CargoOoDestinationInvalidationFacade invalidationFacade;
@InjectMocks
private ProcessMessageServiceImpl processMessageService;
@Captor
private ArgumentCaptor<Declaration> declarationArgumentCaptor;
@Captor
private ArgumentCaptor<Movement> movementArgumentCaptor;
@ParameterizedTest
@DisplayName("Test - Process Message Service")
@MethodSource("provideTestArguments")
void testProcessMessageService(String messageType) {
// Test variables:
String messageId = MESSAGE_ID_PREFIX + messageType;
String movementId = MOVEMENT_ID_PREFIX + messageType;
Message testMessage = null;
TB015CType testTB015CType = null;
MessageTypes cargoMessageType = MessageTypes.fromValue(messageType);
// Mocks/Stubs per test case:
switch (cargoMessageType) {
case TB_007_C:
case TB_014_C:
// TODO: Add needed mocks/stubs when implemented.
break;
case TB_015_C:
testTB015CType = TestDataUtilities.createTB015C(TEST_DEPARTURE_OFFICE, TEST_DESTINATION_OFFICE);
testMessage = TestDataUtilities.createMessage(messageId, messageType, XmlConverter.marshal(testTB015CType,
NamespacesEnum.NTA.getValue(), MessageTypes.TB_015_C.value()));
when(dossierDataService.getMovementById(movementId)).thenReturn(TestDataUtilities.createMovement(movementId));
when(dossierDataService.getMessageById(messageId)).thenReturn(testMessage);
break;
default:
break;
}
// Call ProcessMessageService method:
processMessageService.process(messageId, messageType, movementId);
// Verifications & assertions per test case:
switch (cargoMessageType) {
case TB_007_C:
verify(arrivalNotificationFacade, times(1)).initProcessInstance(movementId, messageId);
break;
case TB_014_C:
verify(invalidationFacade, times(1)).initProcessInstance(movementId, messageId);
break;
case TB_015_C:
verify(dossierDataService, times(1)).getMovementById(movementId);
verify(dossierDataService, times(1)).getMessageById(messageId);
verify(dossierDataService, times(1)).createDeclaration(declarationArgumentCaptor.capture());
verify(dossierDataService, times(1)).updateMovement(movementArgumentCaptor.capture());
verify(mainFacade, times(1)).initProcessInstance(movementId, messageId);
Movement capturedMovement = movementArgumentCaptor.getValue();
Declaration capturedDeclaration = declarationArgumentCaptor.getValue();
assertEquals(testTB015CType.getTransitOperation().getDeclarationType(), capturedMovement.getDeclarationType());
assertEquals(testTB015CType.getHolderOfTheTransitProcedure().getIdentificationNumber(), capturedMovement.getSubmitterIdentification());
assertEquals(testTB015CType.getCustomsOfficeOfDeparture().getReferenceNumber(), capturedMovement.getOfficeOfDeparture());
assertEquals(testTB015CType.getCustomsOfficeOfDestinationDeclared().getReferenceNumber(), capturedMovement.getOfficeOfDestination());
assertEquals(testTB015CType.getConsignment().getCountryOfDestination(), capturedMovement.getCountryOfDestination());
assertEquals(movementId, capturedDeclaration.getMovementId());
assertEquals(messageType, capturedDeclaration.getPayloadType());
assertEquals(testMessage.getPayload(), capturedDeclaration.getPayload());
break;
default:
// Invalid Cargo Message type provided as test argument.
fail();
break;
}
}
private static Stream<Arguments> provideTestArguments() {
return Stream.of(
Arguments.of(MessageTypes.TB_007_C.value()),
Arguments.of(MessageTypes.TB_014_C.value()),
Arguments.of(MessageTypes.TB_015_C.value())
);
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.officeofdeparture.service;
import com.intrasoft.ermis.ddntav5152.messages.GuaranteeType06;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.ReferenceDataAdapter;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeList;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListDomain;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListItem;
import com.intrasoft.ermis.transit.officeofdeparture.domain.ExchangeRate;
import com.intrasoft.ermis.transit.officeofdeparture.domain.ExchangeRates;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
import com.intrasoft.proddev.referencedata.shared.enums.CodelistKeyEnum;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class CurrencyConverterService {
public static final String EUR = "EUR";
// Most of Rate Values in CL048 have 4 decimals
private static final int RATE_SCALE = 4;
private static final int CURRENCY_SCALE = 2;
private static final String RATE_VALUE_ATTRIBUTE_KEY_LITERAL = "RateValue";
private final ReferenceDataAdapter referenceDataAdapter;
/**
* Retrieves from Reference Data and stores in a {@link ExchangeRates} instance all the Exchange Rates for Related currencies,
* excluding EUR currency if set as so.
*/
public ExchangeRates getRelatedExchangeRates(List<GuaranteeType06> guaranteeType06List, boolean excludeEuroCurrency) {
final CodeList codeList = referenceDataAdapter.getCodeList(CodelistKeyEnum.CURRENCY_CODES.getKey(), CodeListDomain.NCTSP5);
Set<String> relatedCurrencies = extractDistinctCurrenciesFromGuarantees(guaranteeType06List, excludeEuroCurrency);
List<CodeListItem> filteredCodelistItemList = codeList.getItems()
.stream()
.filter(item -> relatedCurrencies.contains(item.getCode().toUpperCase(Locale.ROOT)))
.collect(Collectors.toList());
ExchangeRates exchangeRates = new ExchangeRates();
filteredCodelistItemList.forEach(item -> {
BigDecimal euro2CurrencyRate = getRateValueFromCodeListItem(item);
if (euro2CurrencyRate.doubleValue() > 0) {
exchangeRates.putExchangeRate(ExchangeRate.builder()
.currencyCL(item.getCode().toUpperCase(Locale.ROOT))
.euro2CurrencyRate(euro2CurrencyRate)
.currency2EuroRate(BigDecimal.ONE.divide(euro2CurrencyRate, RATE_SCALE, RoundingMode.HALF_EVEN))
.build());
}
});
return exchangeRates;
}
public BigDecimal convertEuro2Currency(BigDecimal amountInEuro, @NonNull String currencyCLTo,
ExchangeRates exchangeRates) {
return amountInEuro.multiply(exchangeRates.getExchangeRate(currencyCLTo).getEuro2CurrencyRate()).setScale(CURRENCY_SCALE, RoundingMode.HALF_EVEN);
}
public BigDecimal convertCurrency2Euro(BigDecimal amountInCurrency, @NonNull String currencyCLFrom,
ExchangeRates exchangeRates) {
return amountInCurrency.multiply(exchangeRates.getExchangeRate(currencyCLFrom).getCurrency2EuroRate()).setScale(CURRENCY_SCALE, RoundingMode.HALF_EVEN);
}
public BigDecimal convertCurrency2Currency(BigDecimal amount, @NonNull String currencyCLFrom,
@NonNull String currencyCLTo, ExchangeRates exchangeRates) {
if (currencyCLFrom.equalsIgnoreCase(currencyCLTo))
return amount;
// If one of the currencies is EUR avoid the unnecessary double conversion
if (EUR.equalsIgnoreCase(currencyCLFrom))
return convertEuro2Currency(amount, currencyCLTo, exchangeRates);
else if (EUR.equalsIgnoreCase(currencyCLTo))
return convertCurrency2Euro(amount, currencyCLFrom, exchangeRates);
else {
// None of the 2 currencies is EUR
return convertEuro2Currency(
convertCurrency2Euro(amount, currencyCLFrom, exchangeRates), currencyCLTo, exchangeRates);
}
}
private Set<String> extractDistinctCurrenciesFromGuarantees(List<GuaranteeType06> guaranteeType06List, boolean excludeEuroCurrency) {
return guaranteeType06List.stream()
.flatMap(guaranteeType06 -> guaranteeType06.getGuaranteeReference().stream())
.map(guaranteeReference -> guaranteeReference.getCurrency().toUpperCase(Locale.ROOT))
.filter(currency -> !excludeEuroCurrency || !EUR.equalsIgnoreCase(currency))
.collect(Collectors.toSet());
}
private BigDecimal getRateValueFromCodeListItem(CodeListItem codeListItem) {
return new BigDecimal(
codeListItem.getAttributes()
.stream()
.filter(attribute -> attribute.getKey().equals(RATE_VALUE_ATTRIBUTE_KEY_LITERAL))
.findFirst()
.orElseThrow(() -> new RuntimeException(
"No Attribute: [" + RATE_VALUE_ATTRIBUTE_KEY_LITERAL + "] found in CodeListItem: "
+ codeListItem.getCode()))
.getValue());
}
}
| package com.intrasoft.ermis.trs.officeofdeparture.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.ddntav5152.messages.GuaranteeReferenceType04;
import com.intrasoft.ermis.ddntav5152.messages.GuaranteeType06;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.ReferenceDataAdapter;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.Attribute;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeList;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListDomain;
import com.intrasoft.ermis.platform.shared.client.reference.data.core.domain.CodeListItem;
import com.intrasoft.ermis.transit.officeofdeparture.domain.ExchangeRates;
import com.intrasoft.ermis.transit.officeofdeparture.service.CurrencyConverterService;
import com.intrasoft.proddev.referencedata.shared.enums.CodelistKeyEnum;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class CurrencyConverterServiceUT {
private static final String RATE_VALUE_ATTRIBUTE_KEY_LITERAL = "RateValue";
private static final int RATE_SCALE = 4;
@Mock
private ReferenceDataAdapter referenceDataAdapter;
@InjectMocks
private CurrencyConverterService currencyConverterService;
@ParameterizedTest
@DisplayName("Test - Get Related Exchange Rates")
@ValueSource(booleans = {true, false})
void testGetRelatedExchangeRates(boolean excludeEuroCurrency) {
// Test data:
CodeList mockCodelist = buildMockCodelist();
List<GuaranteeType06> mockGuaranteeList = buildGuaranteeList();
// Stubs:
when(referenceDataAdapter.getCodeList(CodelistKeyEnum.CURRENCY_CODES.getKey(), CodeListDomain.NCTSP5)).thenReturn(mockCodelist);
// Call tested method:
ExchangeRates result = currencyConverterService.getRelatedExchangeRates(mockGuaranteeList, excludeEuroCurrency);
// Assertions:
try {
result.getExchangeRate("GBP");
// Fail if above call does not throw exception:
fail();
} catch (IllegalArgumentException exception) {
if (!"Currency code not valid or not supported : 'GBP'".equals(exception.getMessage())) {
fail();
}
}
if (excludeEuroCurrency) {
try {
result.getExchangeRate("EUR");
// Fail if above call does not throw exception:
fail();
} catch (IllegalArgumentException exception) {
if (!"Currency code not valid or not supported : 'EUR'".equals(exception.getMessage())) {
fail();
}
}
} else {
assertEquals("EUR", result.getExchangeRate("EUR").getCurrencyCL());
assertEquals(BigDecimal.valueOf(1.0), result.getExchangeRate("EUR").getEuro2CurrencyRate());
assertEquals(BigDecimal.valueOf(1.0).setScale(RATE_SCALE, RoundingMode.HALF_EVEN), result.getExchangeRate("EUR").getCurrency2EuroRate());
}
assertEquals("DKK", result.getExchangeRate("DKK").getCurrencyCL());
assertEquals(BigDecimal.valueOf(5.0), result.getExchangeRate("DKK").getEuro2CurrencyRate());
assertEquals(BigDecimal.valueOf(0.2).setScale(RATE_SCALE, RoundingMode.HALF_EVEN), result.getExchangeRate("DKK").getCurrency2EuroRate());
}
private CodeList buildMockCodelist() {
CodeListItem itemDKK = CodeListItem.builder()
.code("DKK")
.attributes(List.of(Attribute.builder().key(RATE_VALUE_ATTRIBUTE_KEY_LITERAL).value("5.0").build()))
.build();
CodeListItem itemEUR = CodeListItem.builder()
.code("EUR")
.attributes(List.of(Attribute.builder().key(RATE_VALUE_ATTRIBUTE_KEY_LITERAL).value("1.0").build()))
.build();
CodeListItem itemGBP = CodeListItem.builder()
.code("GBP")
.attributes(List.of(Attribute.builder().key(RATE_VALUE_ATTRIBUTE_KEY_LITERAL).value("2.0").build()))
.build();
return CodeList.builder()
.code(CodelistKeyEnum.CURRENCY_CODES.getKey())
.items(List.of(itemDKK, itemEUR, itemGBP))
.build();
}
private List<GuaranteeType06> buildGuaranteeList() {
GuaranteeType06 firstGuarantee = new GuaranteeType06();
GuaranteeReferenceType04 firstGuaranteeReferenceOne = new GuaranteeReferenceType04();
GuaranteeReferenceType04 firstGuaranteeReferenceTwo = new GuaranteeReferenceType04();
firstGuaranteeReferenceOne.setCurrency("DKK");
firstGuaranteeReferenceOne.setAmountConcerned(BigDecimal.TEN);
firstGuaranteeReferenceTwo.setCurrency("EUR");
firstGuaranteeReferenceTwo.setAmountConcerned(BigDecimal.ONE);
firstGuarantee.getGuaranteeReference().addAll(List.of(firstGuaranteeReferenceOne, firstGuaranteeReferenceTwo));
GuaranteeType06 secondGuarantee = new GuaranteeType06();
GuaranteeReferenceType04 secondGuaranteeReferenceOne = new GuaranteeReferenceType04();
secondGuaranteeReferenceOne.setCurrency("DKK");
secondGuaranteeReferenceOne.setAmountConcerned(BigDecimal.TEN);
secondGuarantee.getGuaranteeReference().add(secondGuaranteeReferenceOne);
return new ArrayList<>(List.of(firstGuarantee, secondGuarantee));
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.test.util;
import com.intrasoft.ermis.cargov1.messages.CustomsOfficeOfDepartureType03;
import com.intrasoft.ermis.cargov1.messages.CustomsOfficeOfDestinationActualType03;
import com.intrasoft.ermis.cargov1.messages.CustomsOfficeOfDestinationDeclaredType01;
import com.intrasoft.ermis.cargov1.messages.TB007CType;
import com.intrasoft.ermis.cargov1.messages.TB015CType;
import com.intrasoft.ermis.cargov1.messages.TBConsignmentType;
import com.intrasoft.ermis.cargov1.messages.TBHolderOfTheTransitProcedureType;
import com.intrasoft.ermis.cargov1.messages.TBTransitOperationType;
import com.intrasoft.ermis.cargov1.messages.TransitOperationType02;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Declaration;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TestDataUtilities {
public static Declaration createDeclaration(String movementId, String payload, String payloadType) {
return Declaration.builder().movementId(movementId).payload(payload).payloadType(payloadType).build();
}
public static Movement createMovement(String movementId) {
return Movement.builder().id(movementId).createdDateTime(LocalDateTime.now(ZoneOffset.UTC)).build();
}
public static Message createMessage(String messageId, String messageType, String payload) {
return Message.builder().id(messageId).messageType(messageType).payload(payload).build();
}
public static TB015CType createTB015C(String officeOfDeparture, String officeOfDestination) {
TB015CType tb015cTypeMessage = new TB015CType();
tb015cTypeMessage.setMessageSender("TEST_SENDER");
tb015cTypeMessage.setMessageRecipient("TEST_RECIPIENT");
tb015cTypeMessage.setPreparationDateAndTime(LocalDateTime.now(ZoneOffset.UTC));
tb015cTypeMessage.setTransitOperation(new TBTransitOperationType());
tb015cTypeMessage.getTransitOperation().setLRN("TEST_LRN");
tb015cTypeMessage.getTransitOperation().setDeclarationType("TEST_TYPE");
tb015cTypeMessage.setHolderOfTheTransitProcedure(new TBHolderOfTheTransitProcedureType());
tb015cTypeMessage.getHolderOfTheTransitProcedure().setIdentificationNumber("TEST_IDENTIFICATION");
tb015cTypeMessage.setCustomsOfficeOfDeparture(new CustomsOfficeOfDepartureType03());
tb015cTypeMessage.getCustomsOfficeOfDeparture().setReferenceNumber(officeOfDeparture);
tb015cTypeMessage.setCustomsOfficeOfDestinationDeclared(new CustomsOfficeOfDestinationDeclaredType01());
tb015cTypeMessage.getCustomsOfficeOfDestinationDeclared().setReferenceNumber(officeOfDestination);
tb015cTypeMessage.setConsignment(new TBConsignmentType());
tb015cTypeMessage.getConsignment().setCountryOfDestination(officeOfDestination.substring(0, 2));
return tb015cTypeMessage;
}
public static TB007CType createTB007C(String officeOfDestination) {
TB007CType tb007cTypeMessage = new TB007CType();
tb007cTypeMessage.setMessageSender("TEST_SENDER");
tb007cTypeMessage.setMessageRecipient("TEST_RECIPIENT");
tb007cTypeMessage.setPreparationDateAndTime(LocalDateTime.now(ZoneOffset.UTC));
tb007cTypeMessage.setTransitOperation(new TransitOperationType02());
tb007cTypeMessage.getTransitOperation().setMRN("TEST_MRN");
tb007cTypeMessage.setCustomsOfficeOfDestinationActual(new CustomsOfficeOfDestinationActualType03());
tb007cTypeMessage.getCustomsOfficeOfDestinationActual().setReferenceNumber(officeOfDestination);
return tb007cTypeMessage;
}
}
| null | You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.management.core.service;
import com.intrasoft.ermis.common.json.parsing.JsonConverter;
import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.contracts.core.dto.declaration.common.RegimeEnum;
import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent;
import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService;
import com.intrasoft.ermis.transit.common.enums.DirectionEnum;
import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum;
import com.intrasoft.ermis.transit.common.mappers.MessageTypeMapper;
import com.intrasoft.ermis.transit.management.core.port.inbound.RiskAssessmentMessageProcessingService;
import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService;
import com.intrasoft.ermis.transit.management.core.port.outbound.ProcessMessageCommandProducer;
import com.intrasoft.ermis.transit.management.domain.Message;
import com.intrasoft.ermis.transit.management.domain.Movement;
import com.jayway.jsonpath.JsonPath;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class RiskAssessmentMessageProcessingServiceImpl implements RiskAssessmentMessageProcessingService {
private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter();
private final ErmisLogger log;
private final DossierDataService dossierDataService;
private final ProcessMessageCommandProducer processMessageCommandProducer;
private final GetCountryCodeService getCountryCodeService;
private static final String RISK_ASSESSMENT_SOURCE = "RISK_ASSESSMENT";
private static final String RESPONSE_ID_JSON_PATH = "$.responseId";
@Override
public void processMessage(String messageJson) {
log.info("RiskAssessmentMessageProcessingServiceImpl - processMessage");
RiskAssessmentResponseEvent receivedEvent = JSON_CONVERTER.convertStringToObject(messageJson, RiskAssessmentResponseEvent.class);
if (RegimeEnum.TRANSIT.getCode().equals(receivedEvent.getRegime())) {
String movementId = receivedEvent.getCorrelationKey();
Message message = setUpMessage(messageJson);
message = dossierDataService.persistMessage(message);
dossierDataService.associateMessageWithMovement(message.getId(), movementId);
Movement movement = dossierDataService.getMovementById(movementId, false);
processMessageCommandProducer.publish(message.getId(), message.getMessageType(), movement);
} else {
log.info("Consumed non-Transit RiskAssessmentResponseEvent! Ignoring...");
}
}
protected Message setUpMessage(String messageJson) {
return Message.builder()
.messageIdentification(JsonPath.read(messageJson, RESPONSE_ID_JSON_PATH))
.messageType(RiskAssessmentResponseEvent.class.getSimpleName())
.source(RISK_ASSESSMENT_SOURCE)
.destination(MessageTypeMapper.NTA.concat(getCountryCodeService.getCountryCode()))
.payload(messageJson)
.domain(MessageDomainTypeEnum.ERMIS.name())
.direction(DirectionEnum.RECEIVED.getDirection())
.build();
}
}
| package com.intrasoft.ermis.transit.management.core.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentRequestEvent;
import com.intrasoft.ermis.contracts.core.dto.declaration.riskassessment.v2.RiskAssessmentResponseEvent;
import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService;
import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum;
import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum;
import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum;
import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService;
import com.intrasoft.ermis.transit.management.core.port.outbound.ProcessMessageCommandProducer;
import com.intrasoft.ermis.transit.management.domain.Message;
import com.intrasoft.ermis.transit.management.domain.Movement;
import com.intrasoft.ermis.transit.shared.testing.util.FileHelpers;
import java.util.List;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class RiskAssessmentMessageProcessingServiceImplUT {
@Mock
private ErmisLogger ermisLogger;
@Mock
private DossierDataService dossierDataService;
@Mock
private ProcessMessageCommandProducer processMessageCommandProducer;
@Mock
private GetCountryCodeService getCountryCodeService;
@InjectMocks
private RiskAssessmentMessageProcessingServiceImpl riskAssessmentMessageProcessingService;
@Captor
ArgumentCaptor<Message> messageArgumentCaptor;
@Captor
private ArgumentCaptor<String> messageIdCaptor;
@Captor
private ArgumentCaptor<String> movementIdCaptor;
@Captor
private ArgumentCaptor<String> messageTypeCaptor;
@Captor
ArgumentCaptor<Movement> movementArgumentCaptor;
private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID";
private static final String REQUEST_ID = "TEST_REQUEST_ID";
private static final String RESPONSE_ID = "TEST_RESPONSE_ID";
private static final String DESTINATION = "NTA.DE";
private static final String RISK_ASSESSMENT = "RISK_ASSESSMENT";
private static final String OFFICE_ID = "AA000001";
@Test
@SneakyThrows
void testProcessMessage_success() {
// given
String responseMessageJson = FileHelpers.readClasspathFile("data/RiskAssessmentResponseEvent.json");
String requestMessageJson = FileHelpers.readClasspathFile("data/RiskAssessmentRequestEvent.json");
// when
Message requestMessage = mockRequestMessage(requestMessageJson);
Movement movement = Movement.builder()
.id(MOVEMENT_ID)
.officeRoleType(OfficeRoleTypesEnum.DESTINATION.getValue())
.officeId("AA000001")
.processingStatus(ProcessingStatusTypeEnum.OODEST_AAR_CREATED.getItemCode())
.build();
when(getCountryCodeService.getCountryCode()).thenReturn("DK");
when(dossierDataService.getMovementById(MOVEMENT_ID, false)).thenReturn(movement);
when(dossierDataService.persistMessage(any())).thenAnswer(argument -> {
Message message = argument.getArgument(0);
message.setId(RESPONSE_ID);
return message;
});
riskAssessmentMessageProcessingService.processMessage(responseMessageJson);
// then
verify(dossierDataService, times(1)).persistMessage(messageArgumentCaptor.capture());
verify(dossierDataService, times(1)).associateMessageWithMovement(messageIdCaptor.capture(), movementIdCaptor.capture());
verify(processMessageCommandProducer, times(1)).publish(messageIdCaptor.capture(), messageTypeCaptor.capture(),
movementArgumentCaptor.capture());
assertThat(messageIdCaptor.getValue()).isEqualTo(RESPONSE_ID);
assertThat(movementIdCaptor.getValue()).isEqualTo(MOVEMENT_ID);
assertThat(messageTypeCaptor.getValue()).isEqualTo(RiskAssessmentResponseEvent.class.getSimpleName());
List<Movement> publishedMovements = movementArgumentCaptor.getAllValues();
assertThat(publishedMovements.size()).isEqualTo(1);
assertTrue(publishedMovements.stream()
.filter(m -> m.getOfficeRoleType().equals(OfficeRoleTypesEnum.DESTINATION.getValue()))
.allMatch(m -> m.getOfficeId().equals(OFFICE_ID)));
}
private Message mockRequestMessage(String requestMessageJson) {
return Message.builder()
.messageIdentification("TEST_REQUEST_ID")
.messageType(RiskAssessmentRequestEvent.class.getSimpleName())
.source(DESTINATION)
.destination(RISK_ASSESSMENT)
.domain(MessageDomainTypeEnum.ERMIS.name())
.payload(requestMessageJson)
.build();
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.management.core.service.lrn;
import static com.intrasoft.ermis.transit.management.core.service.lrn.LRNVariablesEnum.*;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.ddntav5152.messages.CC015CType;
import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService;
import com.intrasoft.ermis.transit.common.util.RandomUtil;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
@Service
public class LRNGeneratorSubService {
public static final String VARIABLE_PLACEHOLDER_LEFT = "{";
public static final String VARIABLE_PLACEHOLDER_RIGHT = "}";
private static final Map<Character, Integer> equivalentNumericalValues = new HashMap<>();
static {
equivalentNumericalValues.put('0', 0);
equivalentNumericalValues.put('1', 1);
equivalentNumericalValues.put('2', 2);
equivalentNumericalValues.put('3', 3);
equivalentNumericalValues.put('4', 4);
equivalentNumericalValues.put('5', 5);
equivalentNumericalValues.put('6', 6);
equivalentNumericalValues.put('7', 7);
equivalentNumericalValues.put('8', 8);
equivalentNumericalValues.put('9', 9);
equivalentNumericalValues.put('A', 10);
equivalentNumericalValues.put('B', 12);
equivalentNumericalValues.put('C', 13);
equivalentNumericalValues.put('D', 14);
equivalentNumericalValues.put('E', 15);
equivalentNumericalValues.put('F', 16);
equivalentNumericalValues.put('G', 17);
equivalentNumericalValues.put('H', 18);
equivalentNumericalValues.put('I', 19);
equivalentNumericalValues.put('J', 20);
equivalentNumericalValues.put('K', 21);
equivalentNumericalValues.put('L', 23);
equivalentNumericalValues.put('M', 24);
equivalentNumericalValues.put('N', 25);
equivalentNumericalValues.put('O', 26);
equivalentNumericalValues.put('P', 27);
equivalentNumericalValues.put('Q', 28);
equivalentNumericalValues.put('R', 29);
equivalentNumericalValues.put('S', 30);
equivalentNumericalValues.put('T', 31);
equivalentNumericalValues.put('U', 32);
equivalentNumericalValues.put('V', 34);
equivalentNumericalValues.put('W', 35);
equivalentNumericalValues.put('X', 36);
equivalentNumericalValues.put('Y', 37);
equivalentNumericalValues.put('Z', 38);
}
private static final Pattern LRN_REGEXP = Pattern.compile("^.*\\(.*\\)$");
private final GetCountryCodeService getCountryCodeService;
private final ErmisLogger ermisLogger;
LRNGeneratorSubService(GetCountryCodeService getCountryCodeService, ErmisLogger ermisLogger) {
this.getCountryCodeService = getCountryCodeService;
this.ermisLogger = ermisLogger;
}
public String generateLrn(CC015CType cc015CType, String expression) {
int uniqueIdLengthParameter = 6;
String dateParameter = "";
String value;
List<String> variablesWithParameters = extractVariablesFromExpression(expression);
for (String variableWithParameters : variablesWithParameters) {
// If expression item contains a parameter - exampleItem(exampleParameter):
if (LRN_REGEXP.matcher(variableWithParameters).find()) {
String expressionParameter = variableWithParameters.substring(variableWithParameters.indexOf('(') + 1, variableWithParameters.indexOf(')'));
if (variableWithParameters.contains(UNIQUE_ID.getDescription())
&& variableWithParameters.length() != UNIQUE_ID.getDescription().length()) {
uniqueIdLengthParameter = Integer.parseInt(expressionParameter);
} else if (variableWithParameters.contains(DATE_PREP.getDescription())
&& variableWithParameters.length() != DATE_PREP.getDescription().length()) {
dateParameter = expressionParameter;
}
}
}
value = evalExpression(cc015CType, uniqueIdLengthParameter, dateParameter, expression);
ermisLogger.info("Generated LRN: ".concat(value));
return value;
}
protected String evalExpression(CC015CType cc015CType, int uniqueIdLength, String dateFormat, String expression) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
Properties nameValueMap = new Properties();
extractVariablesWithoutParametersFromExpression(expression).forEach(variableName -> {
LRNVariablesEnum variableEnum =
LRNVariablesEnum.fromDescription(variableName);
if (ObjectUtils.isNotEmpty(variableEnum)) {
switch (variableEnum) {
case DATE_PREP:
nameValueMap.put(DATE_PREP.getDescription(), cc015CType.getPreparationDateAndTime().format(formatter));
break;
case COUNTRY_CODE:
nameValueMap.put(COUNTRY_CODE.getDescription(), getCountryCodeService.getCountryCode());
break;
case OFFICE_OF_DEPARTURE:
nameValueMap.put(OFFICE_OF_DEPARTURE.getDescription(), cc015CType.getCustomsOfficeOfDeparture().getReferenceNumber());
break;
case UNIQUE_ID:
nameValueMap.put(UNIQUE_ID.getDescription(), generateRandomAlphanumeric(uniqueIdLength));
break;
case CHECK_DIGIT:
nameValueMap.put(CHECK_DIGIT.getDescription(), encloseVarInPlaceHolders(CHECK_DIGIT.getDescription())); // Initial Value
break;
default:
break;
}
} else {
ermisLogger.warn("Item of expression: ".concat(variableName)
.concat(" not found in ".concat(LRNVariablesEnum.class.getSimpleName())));
}
});
return parseLrnExpression(expression, nameValueMap);
}
private static String encloseVarInPlaceHolders(String varName) {
return VARIABLE_PLACEHOLDER_LEFT + varName + VARIABLE_PLACEHOLDER_RIGHT;
}
private String parseLrnExpression(String expresion, Properties nameValueMap) {
AtomicReference<String> expressionWithPlaceHolders = new AtomicReference<>(removeEverythingInParentheses(expresion));
AtomicReference<String> parsedExpression = new AtomicReference<>(expressionWithPlaceHolders.get());
nameValueMap.forEach((varName, varValue) -> {
if (!varName.equals(CHECK_DIGIT.getDescription())) {
parsedExpression.set(
StringUtils.replace(parsedExpression.get(), encloseVarInPlaceHolders((String) varName), (String) varValue));
}
}
);
if (nameValueMap.containsKey(CHECK_DIGIT.getDescription())) {
String parsedExpressionWithCheckDigitPlaceHolder = parsedExpression.get();
String parsedExpressionWithoutCheckDigitPlaceHolder =
StringUtils.remove(parsedExpressionWithCheckDigitPlaceHolder, encloseVarInPlaceHolders(CHECK_DIGIT.getDescription()));
String checkDigit = calculateCheckDigit(parsedExpressionWithoutCheckDigitPlaceHolder);
parsedExpression.set(
StringUtils.replace(parsedExpressionWithCheckDigitPlaceHolder,
encloseVarInPlaceHolders(CHECK_DIGIT.getDescription()), checkDigit));
}
return parsedExpression.get();
}
private String generateRandomAlphanumeric(int targetStringLength) {
int leftLimit = 48; // Number '0'.
int rightLimit = 122; // Letter 'z'.
return RandomUtil.generateSecureRandomInts(leftLimit, rightLimit)
.filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString().toUpperCase();
}
public static List<String> extractVariablesFromExpression(String expression) {
return Arrays.stream(StringUtils.substringsBetween(expression, VARIABLE_PLACEHOLDER_LEFT, VARIABLE_PLACEHOLDER_RIGHT))
.map(String::trim)
.collect(Collectors.toList());
}
public static String removeEverythingInParentheses(String expression) {
return expression.replaceAll("\\s*\\([^\\)]*\\)\\s*", "");
}
public static List<String> extractVariablesWithoutParametersFromExpression(String expression) {
return extractVariablesFromExpression(removeEverythingInParentheses(expression));
}
public static String calculateCheckDigit(String id) {
double sum = 0.00;
char[] ch = new char[id.length()];
for (int i = 0; i < id.length(); i++) {
ch[i] = id.toUpperCase().charAt(i);
}
List<Integer> numbers = new ArrayList<>();
for (char c : ch) {
if (equivalentNumericalValues.containsKey(c)) {
Integer num = equivalentNumericalValues.get(c);
numbers.add(num);
}
}
for (int i = 0; i < numbers.size(); i++) {
sum = sum + numbers.get(i) * Math.pow(2, i);
}
if (Math.floorMod((int) sum, 11) != 10) {
return String.valueOf(Math.floorMod((int) sum, 11));
} else {
return "0";
}
}
}
| package com.intrasoft.ermis.transit.management.core.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.ddntav5152.messages.CC015CType;
import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService;
import com.intrasoft.ermis.transit.common.exceptions.NotFoundException;
import com.intrasoft.ermis.transit.management.core.service.lrn.LRNGeneratorSubService;
import com.intrasoft.ermis.transit.management.core.service.lrn.LRNVariablesEnum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Stream;
import javax.xml.bind.JAXBException;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class LRNGeneratorSubServiceUT {
private static final String NEW_LINE = System.getProperty("line.separator");
@Mock
private GetCountryCodeService getCountryCodeService;
@Mock
private ErmisLogger ermisLogger;
@InjectMocks
LRNGeneratorSubService lrnGeneratorSubService;
@ParameterizedTest
@MethodSource("provideLrnFormulas")
void testAssignmentOfLrn(String formula, String expectedLrn, int uidLength, int expectedLength) {
try {
CC015CType cc015CType = XmlConverter.buildMessageFromXML(loadTextFile("CC015C"), CC015CType.class);
if (formula.contains(LRNVariablesEnum.COUNTRY_CODE.getDescription()))
when(getCountryCodeService.getCountryCode()).thenReturn("DK");
String lrn = lrnGeneratorSubService.generateLrn(cc015CType, formula);
String uidRegex = "^([a-zA-Z0-9]){<LENGTH>}$";
assertEquals(expectedLength, lrn.length());
assertTrue(lrn.contains(expectedLrn.replace("<ID>", "")));
assertTrue(lrn.substring(lrn.length() - uidLength).matches(uidRegex.replace("<LENGTH>", uidLength + "")));
} catch (JAXBException e) {
System.exit(-1);
}
}
private String loadTextFile(String messageType) {
String filePath = "data/" + messageType + ".xml";
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
if (inputStream == null) {
throw new NotFoundException("XML file [" + filePath + "] does not exist");
}
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
for (String line; (line = reader.readLine()) != null; ) {
result.append(NEW_LINE);
result.append(line);
}
} catch (IOException e) {
return "";
}
return result.toString().replaceFirst(NEW_LINE, "");
}
public static Stream<Arguments> provideLrnFormulas() {
return Stream.of(
Arguments.of("{DatePrep(yyyyMMdd)}{OfficeOfDeparture}{UniqueId(6)}", "20210614AA000000<ID>", 6, 22),
Arguments.of("{OfficeOfDeparture}{DatePrep(yyyyMMdd)}{UniqueId(6)}", "AA00000020210614<ID>", 6, 22),
Arguments.of("{OfficeOfDeparture}{DatePrep(yyMMddHHmmss)}{UniqueId(2)}", "AA000000210614131816<ID>", 2, 22),
Arguments.of("{CountryCode}{OfficeOfDeparture}{DatePrep(yyMMddHHmm)}{UniqueId(2)}", "DKAA0000002106141318<ID>", 2, 22),
Arguments.of("{CountryCode}-{OfficeOfDeparture}_{DatePrep(yyMMdd)}-重-{UniqueId(2)}", "DK-AA000000_210614-重-<ID>", 2, 23)
);
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.officeofexitfortransit.core.service;
import com.intrasoft.ermis.common.bpmn.core.BpmnEngine;
import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.BpmnFlowVariablesEnum;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.ProcessDefinitionEnum;
import java.util.Map;
import java.util.Objects;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.map.HashedMap;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor(onConstructor_ = {@Autowired})
public class BpmnFlowServiceImpl implements BpmnFlowService {
private final ErmisLogger log;
private final BpmnEngine bpmnEngine;
private final RuntimeService runtimeService;
@Override
public void terminateProcess(String businessKey, String processDefinitionKey, String reason) {
log.info("terminateProcess() on processDefinitionKey: [{}] and businessKey: [{}]", processDefinitionKey, businessKey);
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
.processInstanceBusinessKey(businessKey)
.processDefinitionKey(processDefinitionKey)
.singleResult();
if (Objects.isNull(processInstance) || processInstance.isEnded()) {
log.warn("terminateProcess() with businessKey: [{}] --> NO ACTIVE PROCESS FOUND", businessKey);
return;
}
runtimeService.deleteProcessInstanceIfExists(processInstance.getProcessInstanceId(), reason, false, false, false, false);
}
@Override
public void correlateMessage(String businessKey, String messageName) {
log.info("correlateMessage() on messageType: [{}] and businessKey: [{}]", messageName, businessKey);
CorrelateBpmnMessageCommand correlateBpmnMessageCommand = CorrelateBpmnMessageCommand
.builder()
.messageName(messageName)
.businessKey(businessKey)
.build();
bpmnEngine.correlateMessage(correlateBpmnMessageCommand);
}
@Override
public void startProcess(ProcessDefinitionEnum processDefinition, String businessKey, Map<String, Object> processVariables) {
log.info("startProcess() on processDefinitionKey: [{}] and businessKey: [{}]", processDefinition.getProcessDefinitionKey(), businessKey);
Map<String, Object> finalVars = new HashedMap();
finalVars.put(BpmnFlowVariablesEnum.PROCESS_BUSINESS_KEY.getValue(), businessKey);
finalVars.putAll(processVariables);
bpmnEngine.createProcessInstanceByProcessId(processDefinition.getProcessDefinitionKey(), finalVars);
}
@Override
public void correlateMessageWithValues(String businessKey, String messageName, Map<String, Object> values) {
log.info("correlateMessageWithValues() on messageType : [{}] and businessKey: [{}]", messageName, businessKey);
CorrelateBpmnMessageCommand correlateBpmnMessageCommand = CorrelateBpmnMessageCommand
.builder()
.messageName(messageName)
.businessKey(businessKey)
.values(values)
.build();
bpmnEngine.correlateMessage(correlateBpmnMessageCommand);
}
}
| package com.intrasoft.ermis.transit.officeofexitfortransit.service;
import static java.util.Map.entry;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.bpmn.core.BpmnEngine;
import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.BpmnFlowServiceImpl;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.enums.ProcessDefinitionEnum;
import java.util.Map;
import java.util.UUID;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.runtime.ProcessInstanceQuery;
import org.camunda.bpm.extension.mockito.CamundaMockito;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class BpmnFlowServiceUT {
@Mock
private ErmisLogger ermisLogger;
@Mock
private BpmnEngine bpmnEngine;
@Mock
private RuntimeService runtimeService;
@InjectMocks
private BpmnFlowServiceImpl bpmnFlowService;
@Captor
private ArgumentCaptor<CorrelateBpmnMessageCommand> correlateBpmnMessageCommandArgumentCaptor;
@Test
@DisplayName("Test - Correlate Message with values")
void testCorrelateMessageWithValues() {
String businessKey = UUID.randomUUID().toString();
String messageName = "TEST_NAME";
Map<String, Object> values = Map.ofEntries(
entry("TEST_KEY_1", "TEST_VALUE"),
entry("TEST_KEY_2", true)
);
try {
// Call BpmnFlowService method:
bpmnFlowService.correlateMessageWithValues(businessKey, messageName, values);
// Verification & Assertions:
verify(bpmnEngine, times(1)).correlateMessage(correlateBpmnMessageCommandArgumentCaptor.capture());
assertEquals(businessKey, correlateBpmnMessageCommandArgumentCaptor.getValue().getBusinessKey());
assertEquals(messageName, correlateBpmnMessageCommandArgumentCaptor.getValue().getMessageName());
assertEquals(values.keySet(), correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().keySet());
assertEquals(values.get("TEST_KEY_1"), correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().get("TEST_KEY_1"));
assertEquals(values.get("TEST_KEY_2"), correlateBpmnMessageCommandArgumentCaptor.getValue().getValues().get("TEST_KEY_2"));
} catch (Exception e) {
fail();
}
}
@Test
@DisplayName("Test - Cancel Process Instance - EXISTS")
void testCancelProcessInstanceExists() {
String businessKey = UUID.randomUUID().toString();
String reason = "TEST_REASON";
// Stubs:
// (Use ExecutionEntity to be able to set ProcessInstanceID, valid object as ProcessInstance extends it.)
ExecutionEntity processInstance = new ExecutionEntity();
processInstance.setProcessInstanceId(UUID.randomUUID().toString());
when(runtimeService.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl());
final ProcessInstanceQuery processInstanceQuery = CamundaMockito.mockProcessInstanceQuery(runtimeService)
.singleResult(processInstance);
doNothing().when(runtimeService)
.deleteProcessInstanceIfExists(anyString(), eq(reason), eq(false), eq(false), eq(false), eq(false));
try {
// Call BpmnFlowService method:
bpmnFlowService.terminateProcess(businessKey,
ProcessDefinitionEnum.OOEXIT_FOR_TRANSIT_MAIN_PROCESS.getProcessDefinitionKey(), reason);
// Verifications:
verify(runtimeService, times(1)).createProcessInstanceQuery();
verify(processInstanceQuery).singleResult();
verify(runtimeService, times(1))
.deleteProcessInstanceIfExists(anyString(), eq(reason), eq(false), eq(false), eq(false), eq(false));
} catch (Exception e) {
fail();
}
}
@Test
@DisplayName("Test - Cancel Process Instance - NOT EXISTS")
void testCancelProcessInstanceNotExists() {
String businessKey = UUID.randomUUID().toString();
String reason = "TEST_REASON";
// Stubs:
when(runtimeService.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl());
final ProcessInstanceQuery processInstanceQuery = CamundaMockito.mockProcessInstanceQuery(runtimeService)
.singleResult(null);
try {
// Call BpmnFlowService method:
bpmnFlowService.terminateProcess(businessKey,
ProcessDefinitionEnum.OOEXIT_FOR_TRANSIT_MAIN_PROCESS.getProcessDefinitionKey(), reason);
// Verifications:
verify(runtimeService, times(1)).createProcessInstanceQuery();
verify(processInstanceQuery).singleResult();
verify(runtimeService, times(0))
.deleteProcessInstanceIfExists(anyString(), eq(reason), eq(false), eq(false), eq(false), eq(false));
} catch (Exception e) {
fail();
}
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor;
import com.intrasoft.ermis.transit.common.exceptions.BaseException;
import com.intrasoft.ermis.transit.common.exceptions.NotFoundException;
import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class TimerSetupServiceImpl implements TimerSetupService {
private static final String CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS = "getCargoAutomaticAcceptanceTimerDelayRS";
private static final String CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS = "getCargoArrivalPresentationTimerDelayRS";
private final DossierDataService dossierDataService;
private final TimerDelayExecutor timerDelayExecutor;
@Override
public String getAutomaticAcceptanceTimerDelaySetupString(String movementId) throws BaseException {
try {
Movement movement = dossierDataService.getMovementById(movementId);
return getTimerInfo(movement.getCreatedDateTime(), CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS).getTimerSetupString();
} catch (NotFoundException exception) {
throw new BaseException("Failed to retrieve Movement with ID: " + movementId);
}
}
@Override
public String getArrivalPresentationTimerDelaySetupString(String movementId) throws BaseException {
try {
Movement movement = dossierDataService.getMovementById(movementId);
return getTimerInfo(movement.getCreatedDateTime(), CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS).getTimerSetupString();
} catch (NotFoundException exception) {
throw new BaseException("Failed to retrieve Movement with ID: " + movementId);
}
}
private TimerInfo getTimerInfo(LocalDateTime date, String ruleSet) throws BaseException {
return timerDelayExecutor.getTimerDelayConfig(date, LocalDateTime.now(ZoneOffset.UTC), ruleSet, false)
.orElseThrow(() -> new BaseException("Failed to set up timer from ruleset: " + ruleSet));
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.TimerSetupServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.test.util.TestDataUtilities;
import com.intrasoft.ermis.transit.common.config.timer.TimerDelayExecutor;
import com.intrasoft.ermis.transit.contracts.core.domain.TimerInfo;
import com.intrasoft.ermis.transit.contracts.core.enums.TimeUnitEnum;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class TimerSetupServiceUT {
private static final String MOVEMENT_ID = "TEST_MOVEMENT_ID";
private static final String CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS = "getCargoAutomaticAcceptanceTimerDelayRS";
private static final String CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS = "getCargoArrivalPresentationTimerDelayRS";
@Mock
private DossierDataService dossierDataService;
@Mock
private TimerDelayExecutor timerDelayExecutor;
@InjectMocks
private TimerSetupServiceImpl timerSetupService;
@ParameterizedTest
@DisplayName("Test - Get Automatic Acceptance Timer Delay Setup String")
@ValueSource(strings = {"seconds", "minutes", "hours", "days"})
void testGetAutomaticAcceptanceTimerDelaySetupString(String delayUnit) {
TimerInfo testTimerInfo = createTimerInfo(CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS, delayUnit);
// Stubs/mocks:
when(dossierDataService.getMovementById(MOVEMENT_ID)).thenReturn(TestDataUtilities.createMovement(MOVEMENT_ID));
when(timerDelayExecutor.getTimerDelayConfig(any(), any(), eq(CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS), anyBoolean())).thenReturn(Optional.of(testTimerInfo));
// Call TimerSetupService method:
String returnedValue = timerSetupService.getAutomaticAcceptanceTimerDelaySetupString(MOVEMENT_ID);
// Verifications & Assertions:
verify(dossierDataService).getMovementById(MOVEMENT_ID);
verify(timerDelayExecutor).getTimerDelayConfig(any(), any(), eq(CARGO_AUTOMATIC_ACCEPTANCE_TIMER_DELAY_RS), anyBoolean());
assertEquals(testTimerInfo.getTimerSetupString(), returnedValue);
switch (delayUnit) {
case "seconds":
assertEquals("PT5S", returnedValue);
break;
case "minutes":
assertEquals("PT5M", returnedValue);
break;
case "hours":
assertEquals("PT5H", returnedValue);
break;
case "days":
assertEquals("P5D", returnedValue);
break;
}
}
@ParameterizedTest
@DisplayName("Test - Get Arrival Presentation Timer Delay Setup String")
@ValueSource(strings = {"seconds", "minutes", "hours", "days"})
void testGetArrivalPresentationTimerDelaySetupString(String delayUnit) {
TimerInfo testTimerInfo = createTimerInfo(CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS, delayUnit);
// Stubs/mocks:
when(dossierDataService.getMovementById(MOVEMENT_ID)).thenReturn(TestDataUtilities.createMovement(MOVEMENT_ID));
when(timerDelayExecutor.getTimerDelayConfig(any(), any(), eq(CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS), anyBoolean())).thenReturn(Optional.of(testTimerInfo));
// Call TimerSetupService method:
String returnedValue = timerSetupService.getArrivalPresentationTimerDelaySetupString(MOVEMENT_ID);
// Verifications & Assertions:
verify(dossierDataService).getMovementById(MOVEMENT_ID);
verify(timerDelayExecutor).getTimerDelayConfig(any(), any(), eq(CARGO_ARRIVAL_PRESENTATION_TIMER_DELAY_RS), anyBoolean());
assertEquals(testTimerInfo.getTimerSetupString(), returnedValue);
switch (delayUnit) {
case "seconds":
assertEquals("PT5S", returnedValue);
break;
case "minutes":
assertEquals("PT5M", returnedValue);
break;
case "hours":
assertEquals("PT5H", returnedValue);
break;
case "days":
assertEquals("P5D", returnedValue);
break;
}
}
private TimerInfo createTimerInfo(String ruleSet, String delayUnit) {
TimerInfo testTimerInfo = new TimerInfo();
testTimerInfo.setRuleInstance(ruleSet);
testTimerInfo.setErrorCode("TEST_CODE");
testTimerInfo.setDelay(5);
switch (delayUnit) {
case "seconds":
testTimerInfo.setUnit(TimeUnitEnum.SECONDS);
break;
case "minutes":
testTimerInfo.setUnit(TimeUnitEnum.MINUTES);
break;
case "hours":
testTimerInfo.setUnit(TimeUnitEnum.HOURS);
break;
case "days":
testTimerInfo.setUnit(TimeUnitEnum.DAYS);
break;
}
return testTimerInfo;
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService;
import com.intrasoft.ermis.transit.common.config.services.MRNFormulaConfigurationService;
import com.intrasoft.ermis.transit.common.config.services.MRNGenerationService;
import com.intrasoft.ermis.transit.common.exceptions.BaseException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MRNAllocationServiceImpl implements MRNAllocationService {
private final ErmisLogger logger;
private final DossierDataService dossierDataService;
private final GetCountryCodeService getCountryCodeService;
private final MRNFormulaConfigurationService mrnFormulaConfigurationService;
private final MRNGenerationService mrnGenerationService;
@Override
public String allocateMRN(String movementId) {
Movement movement;
String mrn;
String countryCode = getCountryCodeService.getCountryCode();
try {
movement = dossierDataService.getMovementById(movementId);
String expression = mrnFormulaConfigurationService.retrieveTransitMrnFormula();
mrn = mrnGenerationService.generateMrnJexl(movement.getCreatedDateTime(), movement.getOfficeOfDeparture(), "", countryCode, expression);
assignMrn(movement, countryCode, mrn, expression);
movement.setAcceptanceDateTime(LocalDateTime.now(ZoneOffset.UTC));
dossierDataService.updateMovement(movement);
} catch (Exception e) {
throw new BaseException("Error retrieving movement with ID: " + movementId, e);
}
logger.info("Allocated MRN: " + movement.getMrn() + " and acceptanceDateTime: " + movement.getAcceptanceDateTime() + " on Movement with ID: " + movementId);
return movement.getMrn();
}
private void assignMrn(Movement movement, String countryCode, String mrn, String expression) {
if (dossierDataService.mrnExists(mrn)) {
logger.info("The MRN that was created exists, a new one will be created.");
String newMRN =
mrnGenerationService.generateMrnJexl(movement.getCreatedDateTime(), movement.getOfficeOfDeparture(), movement.getSecurity(), countryCode,
expression);
assignMrn(movement, countryCode, newMRN, expression);
} else {
movement.setMrn(mrn);
}
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.MRNAllocationServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Movement;
import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService;
import com.intrasoft.ermis.transit.common.config.services.MRNFormulaConfigurationService;
import com.intrasoft.ermis.transit.common.config.services.MRNGenerationService;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class MRNAllocationServiceUT {
private static final String MOVEMENT_ID = "MOCK_MOVEMENT_ID";
private static final String OFFICE_OF_DEPARTURE_ID = "MOCK_OFFICE_OF_DEPARTURE_ID";
private static final String COUNTRY_CODE = "MOCK_COUNTRY";
private static final String FORMULA = "MOCK_FORMULA";
private static final String MRN = "MOCK_MRN";
@Mock
private ErmisLogger logger;
@Mock
private DossierDataService dossierDataService;
@Mock
private GetCountryCodeService getCountryCodeService;
@Mock
private MRNFormulaConfigurationService mrnFormulaConfigurationService;
@Mock
private MRNGenerationService mrnGenerationService;
@InjectMocks
private MRNAllocationServiceImpl mrnAllocationService;
@Captor
private ArgumentCaptor<Movement> movementArgumentCaptor;
@Test
@DisplayName("Test - Allocate MRN")
void testAllocateMRN() {
// Test data:
Movement mockMovement = Movement.builder()
.id(MOVEMENT_ID)
.createdDateTime(LocalDateTime.now(ZoneOffset.UTC))
.officeOfDeparture(OFFICE_OF_DEPARTURE_ID)
.build();
// Stubs:
when(getCountryCodeService.getCountryCode()).thenReturn(COUNTRY_CODE);
when(dossierDataService.getMovementById(MOVEMENT_ID)).thenReturn(mockMovement);
when(mrnFormulaConfigurationService.retrieveTransitMrnFormula()).thenReturn(FORMULA);
when(mrnGenerationService.generateMrnJexl(any(LocalDateTime.class), eq(OFFICE_OF_DEPARTURE_ID), eq(""), eq(COUNTRY_CODE), eq(FORMULA)))
.thenReturn(MRN);
when(dossierDataService.mrnExists(MRN)).thenReturn(false);
// Call tested service method:
mrnAllocationService.allocateMRN(MOVEMENT_ID);
// Verifications & Assertions:
verify(mrnGenerationService, times(1)).generateMrnJexl(any(LocalDateTime.class), any(), any(), any(), any());
verify(dossierDataService, times(1)).updateMovement(movementArgumentCaptor.capture());
assertEquals(MRN, movementArgumentCaptor.getValue().getMrn());
assertNotNull(movementArgumentCaptor.getValue().getAcceptanceDateTime());
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.cargov1.messages.MessageTypes;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.outbound.ValidationRequestEventProducer;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationRequestedDomainEvent;
import com.intrasoft.ermis.transit.contracts.validation.enums.ValidationTypeEnum;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ValidationRequestServiceImpl implements ValidationRequestService {
private final ValidationRequestEventProducer validationRequestedEventProducer;
private final DossierDataService dossierDataService;
private final ErmisLogger logger;
@Override
public void publishValidationRequest(String messageId, String movementId) {
logger.error("ENTER publishValidationRequest() " + messageId);
List<String> validationTypes = new ArrayList<>();
Message message = dossierDataService.getMessageById(messageId);
if (MessageTypes.TB_015_C.value().equals(message.getMessageType())) {
validationTypes.addAll(List.of(
ValidationTypeEnum.SEMANTIC_VALIDATION.getType(),
ValidationTypeEnum.XSD_VALIDATION.getType()));
} else if (MessageTypes.TB_007_C.value().equals(message.getMessageType())) {
// TODO: Refine validation types for TB007.
validationTypes.addAll(List.of(
ValidationTypeEnum.SEMANTIC_VALIDATION.getType(),
ValidationTypeEnum.XSD_VALIDATION.getType()));
}
validationRequestedEventProducer.publish(createValidationRequestedDomainEvent(messageId, movementId, validationTypes));
logger.info("EXIT publishValidationRequest() " + messageId);
}
private ValidationRequestedDomainEvent createValidationRequestedDomainEvent(String messageId, String movementId, List<String> validationTypes) {
return ValidationRequestedDomainEvent.builder()
.messageId(messageId)
.movementId(movementId)
.requestedValidationTypeList(validationTypes)
.build();
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.cargov1.messages.MessageTypes;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.outbound.ValidationRequestEventProducer;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ValidationRequestServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationRequestedDomainEvent;
import com.intrasoft.ermis.transit.contracts.validation.enums.ValidationTypeEnum;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ExtendWith(MockitoExtension.class)
class ValidationRequestServiceImplUT {
private static final String MESSAGE_ID = UUID.randomUUID().toString();
private static final String MOVEMENT_ID = UUID.randomUUID().toString();
private static final List<String> MESSAGE_TYPES = List.of(
MessageTypes.TB_015_C.value(),
MessageTypes.TB_007_C.value()
);
@Captor
private ArgumentCaptor<ValidationRequestedDomainEvent> validationRequestedDomainEventArgumentCaptor;
@Mock
private ValidationRequestEventProducer validationRequestedEventProducer;
@Mock
private DossierDataService dossierDataService;
@Mock
private ErmisLogger ermisLogger;
@InjectMocks
private ValidationRequestServiceImpl validationRequestService;
@ParameterizedTest
@MethodSource("arguments")
@DisplayName("Test that a ValidationRequestedDomainEvent is created and passed to the producer")
void test_creationAndPublishOfValidationRequestedEvent(String messageType) {
when(dossierDataService.getMessageById(MESSAGE_ID)).thenReturn(createMessage(messageType));
doNothing().when(validationRequestedEventProducer).publish(any(ValidationRequestedDomainEvent.class));
validationRequestService.publishValidationRequest(MESSAGE_ID, MOVEMENT_ID);
verify(validationRequestedEventProducer, times(1)).publish(validationRequestedDomainEventArgumentCaptor.capture());
assertEquals(MESSAGE_ID, validationRequestedDomainEventArgumentCaptor.getValue().getMessageId());
assertEquals(MOVEMENT_ID, validationRequestedDomainEventArgumentCaptor.getValue().getMovementId());
assertNotNull(validationRequestedDomainEventArgumentCaptor.getValue().getRequestedValidationTypeList());
List<String> requestedValidationTypeList = validationRequestedDomainEventArgumentCaptor.getValue().getRequestedValidationTypeList();
if (MessageTypes.TB_015_C.value().equals(messageType)) {
assertEquals(2, requestedValidationTypeList.size());
assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.XSD_VALIDATION.getType()));
assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.SEMANTIC_VALIDATION.getType()));
} else if (MessageTypes.TB_007_C.value().equals(messageType)) {
// TODO: Refine validation types for TB007.
assertEquals(2, requestedValidationTypeList.size());
assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.XSD_VALIDATION.getType()));
assertTrue(requestedValidationTypeList.contains(ValidationTypeEnum.SEMANTIC_VALIDATION.getType()));
}
}
private static Stream<Arguments> arguments() {
List<Arguments> argumentsList = new ArrayList<>();
for (String expectedMessageType : MESSAGE_TYPES) {
argumentsList.add(Arguments.of(expectedMessageType));
}
return argumentsList.stream();
}
private Message createMessage(String messageType) {
return Message.builder()
.id(MESSAGE_ID)
.messageType(messageType)
.build();
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service;
import com.intrasoft.ermis.cargov1.messages.MessageTypes;
import com.intrasoft.ermis.common.bpmn.core.BpmnEngine;
import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.port.ValidationCompletedEventHandlerService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnFlowVariablesEnum;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationCompletedDomainEvent;
import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum;
import com.intrasoft.ermis.transit.common.exceptions.NotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ValidationCompletedEventHandlerServiceImpl implements ValidationCompletedEventHandlerService {
private final BpmnEngine bpmnEngine;
private final DossierDataService dossierDataService;
@Override
public void onValidationCompletedEvent(ValidationCompletedDomainEvent validationCompletedDomainEvent, String messageType, String mrn)
throws NotFoundException {
CorrelateBpmnMessageCommand correlateBpmnMessageCommand = null;
if (MessageTypes.TB_015_C.value().equals(messageType)) {
correlateBpmnMessageCommand = CorrelateBpmnMessageCommand
.builder()
.businessKey(validationCompletedDomainEvent.getMovementId())
.messageName(BpmnGlobalMessageNamesEnum.TB015_VALIDATION_RESULTS_MESSAGE.getValue())
.value(BpmnFlowVariablesEnum.TB015_VALIDATION_ERRORS_FOUND.getValue(), validationCompletedDomainEvent.isRejecting())
.build();
} else if (MessageTypes.TB_007_C.value().equals(messageType)) {
correlateBpmnMessageCommand = CorrelateBpmnMessageCommand
.builder()
.businessKey(validationCompletedDomainEvent.getMovementId())
.messageName(BpmnGlobalMessageNamesEnum.TB007_VALIDATION_RESULTS_MESSAGE.getValue())
.value(BpmnFlowVariablesEnum.TB007_VALIDATION_ERRORS_FOUND.getValue(), validationCompletedDomainEvent.isRejecting())
.build();
}
if (correlateBpmnMessageCommand != null) {
updateMessageStatus(validationCompletedDomainEvent);
bpmnEngine.correlateMessage(correlateBpmnMessageCommand);
}
}
private void updateMessageStatus(ValidationCompletedDomainEvent validationCompletedDomainEvent) throws NotFoundException {
Message message = dossierDataService.getMessageById(validationCompletedDomainEvent.getMessageId());
if (message != null) {
dossierDataService.updateMessageStatus(message.getId(),
validationCompletedDomainEvent.isRejecting() ? MessageStatusEnum.REJECTED.name() : MessageStatusEnum.ACCEPTED.name());
} else {
throw new NotFoundException("No message found with id: " + validationCompletedDomainEvent.getMessageId());
}
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.bpmn.core.BpmnEngine;
import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand;
import com.intrasoft.ermis.transit.cargoofficeofdestination.adapter.service.ValidationCompletedEventHandlerServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnFlowVariablesEnum;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.events.ValidationCompletedDomainEvent;
import com.intrasoft.ermis.transit.common.enums.MessageStatusEnum;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ValidationCompletedEventHandlerServiceUT {
private static final String MOVEMENT_ID = "MOCK_MOVEMENT_ID";
private static final String MESSAGE_ID = "MOCK_MESSAGE_ID";
private static final String MRN = "MOCK_MRN";
@Mock
private BpmnEngine bpmnEngine;
@Mock
private DossierDataService dossierDataService;
@InjectMocks
private ValidationCompletedEventHandlerServiceImpl validationCompletedEventHandlerService;
@Captor
private ArgumentCaptor<CorrelateBpmnMessageCommand> commandArgumentCaptor;
@ParameterizedTest
@DisplayName("Test - On Validation Completed Event")
@ValueSource(strings = {"TB007C", "TB015C", "UNEXPECTED"})
void testOnValidationCompletedEvent(String messageType) {
// Test data:
Message mockMessage = Message.builder()
.id(MESSAGE_ID)
.messageType(messageType)
.build();
ValidationCompletedDomainEvent mockValidationCompletedDomainEvent = ValidationCompletedDomainEvent.builder()
.movementId(MOVEMENT_ID)
.messageId(MESSAGE_ID)
.rejecting(false)
.build();
// Stubs:
if (!"UNEXPECTED".equals(messageType)) {
when(dossierDataService.getMessageById(MESSAGE_ID)).thenReturn(mockMessage);
}
// Call tested method:
validationCompletedEventHandlerService.onValidationCompletedEvent(mockValidationCompletedDomainEvent, messageType, MRN);
// Verifications & Assertions:
if ("UNEXPECTED".equals(messageType)) {
verify(dossierDataService, times(0)).getMessageById(anyString());
verify(dossierDataService, times(0)).updateMessageStatus(anyString(), anyString());
verify(bpmnEngine, times(0)).correlateMessage(any(CorrelateBpmnMessageCommand.class));
} else {
verify(dossierDataService, times(1)).getMessageById(MESSAGE_ID);
verify(dossierDataService, times(1)).updateMessageStatus(MESSAGE_ID, MessageStatusEnum.ACCEPTED.name());
verify(bpmnEngine, times(1)).correlateMessage(commandArgumentCaptor.capture());
assertEquals(MOVEMENT_ID, commandArgumentCaptor.getValue().getBusinessKey());
if ("TB007C".equals(messageType)) {
assertEquals(BpmnGlobalMessageNamesEnum.TB007_VALIDATION_RESULTS_MESSAGE.getValue(), commandArgumentCaptor.getValue().getMessageName());
assertNotNull(commandArgumentCaptor.getValue().getValues());
assertEquals(false, commandArgumentCaptor.getValue().getValues().get(BpmnFlowVariablesEnum.TB007_VALIDATION_ERRORS_FOUND.getValue()));
} else if ("TB015C".equals(messageType)) {
assertEquals(BpmnGlobalMessageNamesEnum.TB015_VALIDATION_RESULTS_MESSAGE.getValue(), commandArgumentCaptor.getValue().getMessageName());
assertNotNull(commandArgumentCaptor.getValue().getValues());
assertEquals(false, commandArgumentCaptor.getValue().getValues().get(BpmnFlowVariablesEnum.TB015_VALIDATION_ERRORS_FOUND.getValue()));
}
}
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.management.core.service;
import com.intrasoft.ermis.common.json.parsing.JsonConverter;
import com.intrasoft.ermis.common.json.parsing.JsonConverterFactory;
import com.intrasoft.ermis.transit.common.config.services.GetCountryCodeService;
import com.intrasoft.ermis.transit.common.enums.DirectionEnum;
import com.intrasoft.ermis.transit.common.enums.MessageDomainTypeEnum;
import com.intrasoft.ermis.transit.common.util.MessageUtil;
import com.intrasoft.ermis.transit.contracts.management.dto.action.data.StatusRequestEvent;
import com.intrasoft.ermis.transit.management.core.port.outbound.DossierDataService;
import com.intrasoft.ermis.transit.management.core.port.outbound.StatusRequestProducer;
import com.intrasoft.ermis.transit.management.domain.Message;
import com.intrasoft.ermis.transit.shared.security.service.UserDetailsService;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class StatusRequestServiceImpl implements StatusRequestService {
private static final JsonConverter JSON_CONVERTER = JsonConverterFactory.getDefaultJsonConverter();
private final StatusRequestProducer statusRequestProducer;
private final UserDetailsService userDetailsService;
private final GetCountryCodeService getCountryCodeService;
private final DossierDataService dossierDataService;
// TODO: Should be refactored to use action system
@Override
public void handleStatusRequest(StatusRequestEvent statusRequestEvent) {
statusRequestEvent.setRequestId(UUID.randomUUID().toString());
Message message = Message.builder()
.messageIdentification(MessageUtil.generateMessageIdentification())
.messageType(StatusRequestEvent.class.getSimpleName())
.source(userDetailsService.getUsername())
.destination("NTA." + getCountryCodeService.getCountryCode())
.payload(JSON_CONVERTER.convertToJsonString(statusRequestEvent))
.domain(MessageDomainTypeEnum.ERMIS.name())
.direction(DirectionEnum.RECEIVED.getDirection())
.build();
message = dossierDataService.persistMessage(message);
dossierDataService.associateMessageWithMovement(message.getId(), statusRequestEvent.getMovementId());
statusRequestProducer.publish(statusRequestEvent);
}
}
| package com.intrasoft.ermis.transit.officeofexitfortransit.service;
import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createIE094Message;
import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.createIE168Message;
import static com.intrasoft.ermis.transit.officeofexitfortransit.util.DataGenerators.generateRandomMRN;
import static com.intrasoft.ermis.transit.officeofexitfortransit.util.Stubs.stubSaveMessage;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.ddntav5152.messages.CD094CType;
import com.intrasoft.ermis.ddntav5152.messages.CD168CType;
import com.intrasoft.ermis.ddntav5152.messages.MessageTypes;
import com.intrasoft.ermis.transit.common.enums.OfficeRoleTypesEnum;
import com.intrasoft.ermis.transit.common.enums.ProcessingStatusTypeEnum;
import com.intrasoft.ermis.transit.officeofexitfortransit.core.outbound.DDNTAMessageProducer;
import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.DossierDataService;
import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.GenerateMessageService;
import com.intrasoft.ermis.transit.officeofexitfortransit.core.service.StatusRequestServiceImpl;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Message;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.MessageOverview;
import com.intrasoft.ermis.transit.officeofexitfortransit.domain.Movement;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class StatusRequestServiceUT {
private final String MOVEMENT_ID = UUID.randomUUID().toString();
private final String MRN = generateRandomMRN();
private static final String IE094_MESSAGE_ID = "IE094_MESSAGE_ID";
private static final String IE168_MESSAGE_ID = "IE168_MESSAGE_ID";
@Mock
private DossierDataService dossierDataService;
@Mock
private GenerateMessageService generateMessageService;
@Mock
private DDNTAMessageProducer ddntaMessageProducer;
@InjectMocks
private StatusRequestServiceImpl statusReportRequestService;
@Captor
private ArgumentCaptor<String> xmlArgumentCaptor;
@Test
@DisplayName("Test - Handle IE094 Status Report Request")
void testHandleIE094StatusRequest() {
System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true");
// Stubs:
Movement movement = createMovement(MOVEMENT_ID);
CD094CType cd094cTypeMessage = createIE094Message(MRN);
CD168CType cd168cTypeMessage = createIE168Message(MRN);
List<MessageOverview> messageOverviewList = createMessageOverviewList();
try {
// Mocks:
when(dossierDataService.getMovementByCriteria(MRN, OfficeRoleTypesEnum.EXIT.getValue(), "IE094_EXIT_OFFICE_REF_NUM")).thenReturn(movement);
doNothing().when(generateMessageService).generateIE095(eq(MOVEMENT_ID), any(), any());
when(dossierDataService.getMessageById(IE094_MESSAGE_ID))
.thenReturn(getMessage(MessageTypes.CD_094_C.value(), XmlConverter.marshal(cd094cTypeMessage)));
when(dossierDataService.getMessageById(IE168_MESSAGE_ID))
.thenReturn(getMessage(MessageTypes.CD_168_C.value(), XmlConverter.marshal(cd168cTypeMessage)));
when(dossierDataService.getMessagesOverview(MOVEMENT_ID, MessageTypes.CD_168_C.value())).thenReturn(messageOverviewList);
when(dossierDataService.saveMessage(any())).thenAnswer(stubSaveMessage());
doNothing().when(dossierDataService).associateMessageWithMovement(any(), eq(MOVEMENT_ID));
// Call StatusRequestService method:
statusReportRequestService.handleIE094StatusRequest(MRN, IE094_MESSAGE_ID, "IE094_EXIT_OFFICE_REF_NUM");
// Verifications & Assertions:
verify(ddntaMessageProducer, times(1)).publish(xmlArgumentCaptor.capture(), eq(MOVEMENT_ID), eq(MessageTypes.CD_168_C.value()));
CD168CType cd168cTypeMessageOut = XmlConverter.buildMessageFromXML(xmlArgumentCaptor.getValue(), CD168CType.class);
verify(dossierDataService, times(1)).getMovementByCriteria(MRN, OfficeRoleTypesEnum.EXIT.getValue(), "IE094_EXIT_OFFICE_REF_NUM");
verify(dossierDataService, times(1)).getMessageById(IE094_MESSAGE_ID);
verify(dossierDataService, times(1)).getMessageById(IE168_MESSAGE_ID);
verify(dossierDataService, times(1)).getMessagesOverview(MOVEMENT_ID, MessageTypes.CD_168_C.value());
verify(dossierDataService, times(1)).saveMessage(any());
verify(dossierDataService, times(1)).associateMessageWithMovement(any(), eq(MOVEMENT_ID));
assertEquals(cd168cTypeMessage.getMessageSender(), cd168cTypeMessageOut.getMessageSender());
assertEquals(cd168cTypeMessage.getMessageRecipient(), cd168cTypeMessageOut.getMessageRecipient());
assertEquals(cd168cTypeMessage.getTransitOperation().getMRN(), cd168cTypeMessageOut.getTransitOperation().getMRN());
assertNotEquals(cd168cTypeMessage.getMessageIdentification(), cd168cTypeMessageOut.getMessageIdentification());
assertNotEquals(cd168cTypeMessage.getPreparationDateAndTime(), cd168cTypeMessageOut.getPreparationDateAndTime());
} catch (Exception e) {
fail();
}
}
private Movement createMovement(String movementId) {
return Movement.builder()
.id(movementId)
.mrn(MRN)
.processingStatus(ProcessingStatusTypeEnum.OOTRXS_MOVEMENT_LEFT_EUROPEAN_CUSTOMS_SECURITY_AREA.getItemCode())
.officeRoleType(OfficeRoleTypesEnum.EXIT.getValue())
.officeId("DK_TEST_OFFICE_ID")
.build();
}
private List<MessageOverview> createMessageOverviewList() {
List<MessageOverview> messageOverviewList = new ArrayList<>();
MessageOverview ie168MessageOverview = new MessageOverview();
ie168MessageOverview.setMessageType(MessageTypes.CD_168_C.value());
ie168MessageOverview.setId(IE168_MESSAGE_ID);
messageOverviewList.add(ie168MessageOverview);
return messageOverviewList;
}
private Message getMessage(String messageType, String payload) {
return Message.builder()
.id(UUID.randomUUID().toString())
.messageIdentification(UUID.randomUUID().toString())
.messageType(messageType)
.source("DEPARTURE")
.destination("EXIT")
.domain("COMMON")
.createdDateTime(LocalDateTime.now(ZoneOffset.UTC))
.payload(payload)
.build();
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.common.bpmn.core.BpmnEngine;
import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum;
import com.intrasoft.ermis.transit.common.exceptions.BaseException;
import lombok.RequiredArgsConstructor;
import org.camunda.bpm.engine.MismatchingMessageCorrelationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ArrivalNotificationServiceImpl implements ArrivalNotificationService {
private static final String ERROR_MESSAGE_PREFIX = "Failed to correlate {" + BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue()
+ "} BPMN message for Movement with ID: ";
private static final String ERROR_MESSAGE_SUFFIX = ". The main process is either past the related await point, is finished or does not exist.";
private final BpmnEngine bpmnEngine;
@Override
public void continueMainProcess(String movementId) throws BaseException {
CorrelateBpmnMessageCommand command = CorrelateBpmnMessageCommand.builder()
.messageName(BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue())
.businessKey(movementId)
.build();
try {
bpmnEngine.correlateMessage(command);
} catch (MismatchingMessageCorrelationException exception) {
throw new BaseException(ERROR_MESSAGE_PREFIX + movementId + ERROR_MESSAGE_SUFFIX);
}
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import com.intrasoft.ermis.common.bpmn.core.BpmnEngine;
import com.intrasoft.ermis.common.bpmn.core.CorrelateBpmnMessageCommand;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.ArrivalNotificationServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.enums.BpmnGlobalMessageNamesEnum;
import com.intrasoft.ermis.transit.common.exceptions.BaseException;
import org.camunda.bpm.engine.MismatchingMessageCorrelationException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class ArrivalNotificationServiceUT {
private static final String ERROR_MESSAGE_PREFIX = "Failed to correlate {" + BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue()
+ "} BPMN message for Movement with ID: ";
private static final String ERROR_MESSAGE_SUFFIX = ". The main process is either past the related await point, is finished or does not exist.";
private static final String MOVEMENT_ID = "MOCK_MOVEMENT_ID";
@Mock
private BpmnEngine bpmnEngine;
@InjectMocks
private ArrivalNotificationServiceImpl arrivalNotificationService;
@Captor
private ArgumentCaptor<CorrelateBpmnMessageCommand> commandArgumentCaptor;
@ParameterizedTest
@DisplayName("Test - Continue Main Process")
@ValueSource(booleans = {true, false})
void testContinueMainProcess(boolean successfulCorrelation) {
if (successfulCorrelation) {
// Stub:
doNothing().when(bpmnEngine).correlateMessage(any());
// Call tested service method:
arrivalNotificationService.continueMainProcess(MOVEMENT_ID);
// Verification & Assertions:
verify(bpmnEngine, times(1)).correlateMessage(commandArgumentCaptor.capture());
assertEquals(BpmnGlobalMessageNamesEnum.TB007_MESSAGE_RECEIVED_MESSAGE.getValue(), commandArgumentCaptor.getValue().getMessageName());
assertEquals(MOVEMENT_ID, commandArgumentCaptor.getValue().getBusinessKey());
} else {
// Stub:
doThrow(new MismatchingMessageCorrelationException("ERROR")).when(bpmnEngine).correlateMessage(any());
// Call tested service method:
Throwable exception = assertThrows(BaseException.class, () ->
arrivalNotificationService.continueMainProcess(MOVEMENT_ID));
// Assertion:
assertEquals(ERROR_MESSAGE_PREFIX + MOVEMENT_ID + ERROR_MESSAGE_SUFFIX, exception.getMessage());
}
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.validation.service;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.common.enums.ValidationRequestPropertyKeyEnum;
import com.intrasoft.ermis.transit.common.exceptions.RetryableException;
import com.intrasoft.ermis.transit.validation.configuration.ValidationRetryConfigurationProperties;
import com.intrasoft.ermis.transit.validation.enums.BpmnFlowVariablesEnum;
import com.intrasoft.ermis.transit.validation.enums.ValidationProcessInstanceEnum;
import com.intrasoft.ermis.transit.validation.events.ValidationRequestedDomainEvent;
import com.intrasoft.ermis.transit.validation.process.MainValidationFlowFacade;
import lombok.RequiredArgsConstructor;
import org.camunda.bpm.engine.RuntimeService;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class InitiateValidationServiceImpl implements InitiateValidationService {
private final MainValidationFlowFacade mainValidationFlowFacade;
private final RuntimeService runtimeService;
private final ErmisLogger ermisLogger;
// NOTE: Following bean is used in @Retryable SpEL expressions.
private final ValidationRetryConfigurationProperties validationRetryConfigurationProperties;
// TODO: Should probably add a @Recover method for RetryableException.class so that on complete failure, IE Message gets rejected.
@Override
@Retryable(value = {RetryableException.class}, maxAttemptsExpression = "#{@validationRetryConfigurationProperties.getMaxAttempts()}",
backoff = @Backoff(delayExpression = "#{@validationRetryConfigurationProperties.getDelay()}",
multiplierExpression = "#{@validationRetryConfigurationProperties.getMultiplier()}"))
public void initiateValidationProcessRetryable(ValidationRequestedDomainEvent validationRequest) {
// Check if validation is already running and throw exception to trigger retries:
checkAndThrowIfValidationAlreadyRunning(validationRequest);
// If no RetryableException was thrown, it is safe to initiate validation:
mainValidationFlowFacade.initProcessInstance(validationRequest);
}
@Override
public void initiateValidationProcess(ValidationRequestedDomainEvent validationRequest) {
mainValidationFlowFacade.initProcessInstance(validationRequest);
}
private void checkAndThrowIfValidationAlreadyRunning(ValidationRequestedDomainEvent validationRequest) throws RetryableException {
// Retrieve LRN from request event properties:
String lrn = validationRequest.getProperties().get(ValidationRequestPropertyKeyEnum.LRN.getValue());
// Query Camunda to check if there is a running process for this LRN:
boolean isValidationRunningForCurrentLRN = !runtimeService.createProcessInstanceQuery()
.processDefinitionKey(ValidationProcessInstanceEnum.TRS_MAIN_VALIDATION_FLOW.getId())
.variableValueEquals(BpmnFlowVariablesEnum.LRN.getValue(), lrn)
.active()
.list()
.isEmpty();
ermisLogger.info("Validation process for LRN: " + lrn
+ (isValidationRunningForCurrentLRN ? " is already running. Will retry..." : " is not running. Continuing..."));
if (isValidationRunningForCurrentLRN) {
throw new RetryableException("Validation already underway for LRN: " + lrn);
}
}
}
| package com.intrasoft.ermis.transit.validation.service;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.common.logging.ErmisLogger;
import com.intrasoft.ermis.transit.common.enums.ValidationRequestPropertyKeyEnum;
import com.intrasoft.ermis.transit.common.exceptions.RetryableException;
import com.intrasoft.ermis.transit.validation.configuration.ValidationRetryConfigurationProperties;
import com.intrasoft.ermis.transit.validation.events.ValidationRequestedDomainEvent;
import com.intrasoft.ermis.transit.validation.process.MainValidationFlowFacade;
import com.intrasoft.ermis.transit.validation.service.InitiateValidationServiceUT.TestConfig;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.extension.mockito.CamundaMockito;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.test.context.ContextConfiguration;
@SpringBootTest
@ContextConfiguration(classes = TestConfig.class)
class InitiateValidationServiceUT {
public static final int TEST_RETRIES = 5;
private static final String LRN = "TEST_LRN";
@MockBean
private MainValidationFlowFacade mainValidationFlowFacade;
@MockBean
private RuntimeService runtimeService;
@MockBean
private ErmisLogger ermisLogger;
@Autowired
private InitiateValidationService initiateValidationService;
@ParameterizedTest
@DisplayName("Test - Initiate Validation Process - Retryable")
@ValueSource(booleans = {true, false})
void testInitiateValidationProcessRetryable(boolean processRunning) {
// Mock the behavior to simulate that no validation is running for LRN:
when(runtimeService.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl());
if (processRunning) {
// Using ExecutionEntity as ProcessInstance extends it:
ExecutionEntity processInstance = new ExecutionEntity();
CamundaMockito.mockProcessInstanceQuery(runtimeService).list(List.of(processInstance));
// Call the service method:
assertThrows(RetryableException.class, () -> initiateValidationService.initiateValidationProcessRetryable(buildRequestEvent()));
// Verify that initProcessInstance is not called when retries are triggered:
verify(mainValidationFlowFacade, never()).initProcessInstance(any());
// RuntimeService should be queried #maxAttempts amount of times:
verify(runtimeService, times(TEST_RETRIES)).createProcessInstanceQuery();
} else {
CamundaMockito.mockProcessInstanceQuery(runtimeService).list(Collections.emptyList());
// Call the service method:
initiateValidationService.initiateValidationProcessRetryable(buildRequestEvent());
// Verify that initProcessInstance is called once
verify(mainValidationFlowFacade, times(1)).initProcessInstance(any());
}
}
@Test
@DisplayName("Test - Initiate Validation Process")
void testInitiateValidationProcessRetryable() {
// Call the service method:
initiateValidationService.initiateValidationProcess(buildRequestEvent());
// Verify that initProcessInstance is called once
verify(mainValidationFlowFacade, times(1)).initProcessInstance(any());
}
private ValidationRequestedDomainEvent buildRequestEvent() {
return ValidationRequestedDomainEvent.builder()
.properties(Map.of(ValidationRequestPropertyKeyEnum.LRN.getValue(), LRN))
.build();
}
@EnableRetry
@Configuration
@Import(InitiateValidationServiceImpl.class)
public static class TestConfig {
@Bean(name = "validationRetryConfigurationProperties")
public ValidationRetryConfigurationProperties validationRetryConfigurationProperties() {
return new ValidationRetryConfigurationProperties() {
@Override
public int getMaxAttempts() {
return TEST_RETRIES;
}
@Override
public long getDelay() {
return 100;
}
@Override
public double getMultiplier() {
return 1.5;
}
};
}
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
package com.intrasoft.ermis.transit.cargoofficeofdestination.core.service;
import com.intrasoft.ermis.cargov1.messages.TB015CType;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.transit.cargoofficeofdestination.domain.Message;
import com.intrasoft.ermis.transit.common.enums.AdditionalDeclarationTypeEnum;
import javax.xml.bind.JAXBException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class DeclarationRegistrationServiceImpl implements DeclarationRegistrationService {
private final DossierDataService dossierDataService;
@Override
public boolean isDeclarationPrelodged(String messageId) throws JAXBException {
Message tb015c = dossierDataService.getMessageById(messageId);
TB015CType tb015cType = XmlConverter.buildMessageFromXML(tb015c.getPayload(), TB015CType.class);
return AdditionalDeclarationTypeEnum.DECLARATION_TYPE_D.getType().equals(tb015cType.getTransitOperation().getAdditionalDeclarationType());
}
}
| package com.intrasoft.ermis.transit.cargoofficeofdestination.test.service;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.intrasoft.ermis.cargov1.messages.MessageTypes;
import com.intrasoft.ermis.cargov1.messages.TB015CType;
import com.intrasoft.ermis.common.xml.parsing.XmlConverter;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DeclarationRegistrationServiceImpl;
import com.intrasoft.ermis.transit.cargoofficeofdestination.core.service.DossierDataService;
import com.intrasoft.ermis.transit.cargoofficeofdestination.test.util.TestDataUtilities;
import com.intrasoft.ermis.transit.common.enums.AdditionalDeclarationTypeEnum;
import com.intrasoft.ermis.transit.shared.testing.util.FileHelpers;
import java.util.UUID;
import javax.xml.bind.JAXBException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class DeclarationRegistrationServiceUT {
private static final String MESSAGE_ID = UUID.randomUUID().toString();
@Mock
private DossierDataService dossierDataService;
@InjectMocks
private DeclarationRegistrationServiceImpl declarationRegistrationService;
@ParameterizedTest
@DisplayName("Test if the TB015C declaration is prelodged ")
@ValueSource(strings = {"A", "D"})
void test_isDeclarationPrelodged(String additionalDeclarationType) throws JAXBException {
String tb015cStringXml = FileHelpers.xmlToString(MessageTypes.TB_015_C.value() + ".xml");
TB015CType tb015CType = XmlConverter.buildMessageFromXML(tb015cStringXml, TB015CType.class);
tb015CType.getTransitOperation().setAdditionalDeclarationType(additionalDeclarationType);
String updatedXmlString = XmlConverter.marshal(tb015CType);
when(dossierDataService.getMessageById(MESSAGE_ID)).thenReturn(
TestDataUtilities.createMessage(MESSAGE_ID, MessageTypes.TB_015_C.value(), updatedXmlString));
boolean isPrelodged = declarationRegistrationService.isDeclarationPrelodged(MESSAGE_ID);
if (AdditionalDeclarationTypeEnum.DECLARATION_TYPE_D.getType().equals(additionalDeclarationType)) {
assertTrue(isPrelodged);
} else {
assertFalse(isPrelodged);
}
}
}
| You are a powerful Java unit test generator. Your task is to create a comprehensive unit test for the given Java class. |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 33