diff --git a/src/test/java/com/iemr/common/controller/beneficiary/BeneficiaryRegistrationControllerTest.java b/src/test/java/com/iemr/common/controller/beneficiary/BeneficiaryRegistrationControllerTest.java index 24da92d4..b6aba3d1 100644 --- a/src/test/java/com/iemr/common/controller/beneficiary/BeneficiaryRegistrationControllerTest.java +++ b/src/test/java/com/iemr/common/controller/beneficiary/BeneficiaryRegistrationControllerTest.java @@ -1,35 +1,43 @@ -/* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution -* -* Copyright (C) "Piramal Swasthya Management and Research Institute" -* -* This file is part of AMRIT. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation, either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see https://www.gnu.org/licenses/. -*/ package com.iemr.common.controller.beneficiary; -import static org.assertj.core.api.Assertions.fail; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONObject; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.springframework.test.context.event.annotation.BeforeTestClass; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import com.iemr.common.data.beneficiary.Beneficiary; +import com.iemr.common.data.beneficiary.BenPhoneMap; +import com.iemr.common.data.beneficiary.BenRelationshipType; +import com.iemr.common.data.beneficiary.BeneficiaryEducation; +import com.iemr.common.data.beneficiary.BeneficiaryOccupation; +import com.iemr.common.data.beneficiary.BeneficiaryRegistrationData; +import com.iemr.common.data.beneficiary.GovtIdentityType; +import com.iemr.common.data.beneficiary.SexualOrientation; +import com.iemr.common.data.directory.Directory; +import com.iemr.common.data.location.States; +import com.iemr.common.data.userbeneficiarydata.Community; +import com.iemr.common.data.userbeneficiarydata.Gender; +import com.iemr.common.data.userbeneficiarydata.Language; +import com.iemr.common.data.userbeneficiarydata.MaritalStatus; +import com.iemr.common.data.userbeneficiarydata.Status; +import com.iemr.common.data.userbeneficiarydata.Title; import com.iemr.common.model.beneficiary.BeneficiaryModel; import com.iemr.common.service.beneficiary.BenRelationshipTypeService; import com.iemr.common.service.beneficiary.BeneficiaryOccupationService; @@ -37,9 +45,7 @@ import com.iemr.common.service.beneficiary.IEMRBeneficiaryTypeService; import com.iemr.common.service.beneficiary.IEMRSearchUserService; import com.iemr.common.service.beneficiary.RegisterBenificiaryService; -import com.iemr.common.service.beneficiary.RegisterBenificiaryServiceImpl; import com.iemr.common.service.beneficiary.SexualOrientationService; -import com.iemr.common.service.callhandling.CalltypeService; import com.iemr.common.service.directory.DirectoryService; import com.iemr.common.service.location.LocationService; import com.iemr.common.service.userbeneficiarydata.CommunityService; @@ -49,53 +55,369 @@ import com.iemr.common.service.userbeneficiarydata.MaritalStatusService; import com.iemr.common.service.userbeneficiarydata.StatusService; import com.iemr.common.service.userbeneficiarydata.TitleService; -import com.iemr.common.utils.mapper.InputMapper; - -public class BeneficiaryRegistrationControllerTest { - - private static InputMapper inputMapper = new InputMapper(); - - private static RegisterBenificiaryService registerBenificiaryService; - private static IEMRBeneficiaryTypeService iemrBeneficiaryTypeService; - private static IEMRSearchUserService iemrSearchUserService; - private static EducationService educationService; - private static TitleService titleService; - private static StatusService statusService; - private static LocationService locationService; - private static GenderService genderService; - private static MaritalStatusService maritalStatusService; - private static CommunityService communityService; - private static DirectoryService directoryService; - private static SexualOrientationService sexualOrientationService; - private static LanguageService languageService; - private static BenRelationshipTypeService benRelationshipTypeService; - private static BeneficiaryOccupationService beneficiaryOccupationService; - private static GovtIdentityTypeService govtIdentityTypeService; - private static CalltypeService calltypeService; - private static BeneficiaryModel benPos; - private static BeneficiaryModel benNeg; - static String benData = "{i_bendemographics:{},benPhoneMaps:[{}]}"; - - @BeforeTestClass - public void makeBenefciaryRegistration() { -// try { -// registerBenificiaryService = mock(RegisterBenificiaryServiceImpl.class); -// benPos = inputMapper.gson().fromJson(benData, BeneficiaryModel.class); -// benNeg = inputMapper.gson().fromJson(benData, BeneficiaryModel.class); -// benNeg.setBeneficiaryRegID(0L); -// //when(registerBenificiaryService.updateBenificiary(benPos,"")).thenReturn(1); -// //when(registerBenificiaryService.updateBenificiary(benNeg)).thenReturn(0); -// } catch (Exception e) { -// fail("failed with error " + e.getMessage()); -// } +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class BeneficiaryRegistrationControllerTest { + + @InjectMocks + BeneficiaryRegistrationController beneficiaryRegistrationController; + @Mock + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + private static final String AUTHORIZATION = "authorization"; + @Mock + private RegisterBenificiaryService registerBenificiaryService; + @Mock + private IEMRBeneficiaryTypeService iemrBeneficiaryTypeService; + @Mock + private IEMRSearchUserService iemrSearchUserService; + @Mock + private EducationService educationService; + @Mock + private TitleService titleService; + @Mock + private StatusService statusService; + @Mock + private LocationService locationService; + @Mock + private GenderService genderService; + @Mock + private MaritalStatusService maritalStatusService; + @Mock + private CommunityService communityService; + @Mock + private DirectoryService directoryService; + @Mock + private SexualOrientationService sexualOrientationService; + @Mock + private LanguageService languageService; + @Mock + private BenRelationshipTypeService benRelationshipTypeService; + @Mock + private BeneficiaryOccupationService beneficiaryOccupationService; + @Mock + private GovtIdentityTypeService govtIdentityTypeService; + + @Test + void testCreateBeneficiary() throws Exception { + + OutputResponse response = new OutputResponse(); + + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + + BeneficiaryModel beneficiaryModel = new BeneficiaryModel(); + + beneficiaryModel.setBeneficiaryID("Ben ID"); + beneficiaryModel.setBeneficiaryRegID(123L); + + String expResp = beneficiaryModel.toString(); + + when(registerBenificiaryService.save(beneficiaryModel, httpRequest)).thenReturn(expResp); + + logger.info("Create beneficiary request " + beneficiaryModel); + + String resp = beneficiaryRegistrationController.createBeneficiary(beneficiaryModel, httpRequest); + + logger.info("create beneficiary response " + response.toString()); + + Assertions.assertEquals(resp, + beneficiaryRegistrationController.createBeneficiary(beneficiaryModel, httpRequest)); + + } + + @Test + void testCreateBeneficiary_Exception() throws Exception { + // Arrange + String errorMessage = "Failed to get directories"; + + // Act + String result = beneficiaryRegistrationController.createBeneficiary(any(), any()); + + // Assert + assertNotNull(result); + assertTrue(result.contains("error")); } @Test - public void updateBeneficiaryTest() { -// //assertTrue("Updated beneficiary with ben id " + benPos.getBeneficiaryID(), -// // registerBenificiaryService.updateBenificiary(benPos) == 1); -// int update = registerBenificiaryService.updateBenificiary(benPos); -// assertEquals(update, 0); + void testSearchUserByID() throws Exception { + + OutputResponse response = new OutputResponse(); + + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + + String auth = httpRequest.getHeader(AUTHORIZATION); + + BeneficiaryModel benificiaryDetails = new BeneficiaryModel(); + benificiaryDetails.setBeneficiaryRegID(123L); + benificiaryDetails.setBeneficiaryID("ab"); + benificiaryDetails.setIs1097(true); + benificiaryDetails.setHealthID("abc"); + benificiaryDetails.setHealthIDNumber("bcd"); + benificiaryDetails.setFamilyId("vfd"); + benificiaryDetails.setIdentity("cvf"); + String request = benificiaryDetails.toString(); + logger.info("Search user by ID request " + request); + logger.debug(benificiaryDetails.toString()); + List iBeneficiary = new ArrayList(); + iBeneficiary.add(benificiaryDetails); + + String expResp = beneficiaryRegistrationController.searchUserByID(request, httpRequest); + String expResp1 = beneficiaryRegistrationController.searchUserByID(request, httpRequest); + String expResp2 = beneficiaryRegistrationController.searchUserByID(request, httpRequest); + String expResp3 = beneficiaryRegistrationController.searchUserByID(request, httpRequest); + String expResp4 = beneficiaryRegistrationController.searchUserByID(request, httpRequest); + String expResp5 = beneficiaryRegistrationController.searchUserByID(request, httpRequest); + + try { + response.setResponse(iBeneficiary.toString()); + logger.info("Search user by ID response size " + + (iBeneficiary != null ? iBeneficiary.size() : "No Beneficiary Found")); + } catch (Exception e) { + logger.error("search user failed with error " + e.getMessage()); + response.setError(e); + } + assertNotNull(benificiaryDetails.getBeneficiaryID()); + assertNotNull(benificiaryDetails.getBeneficiaryRegID()); + assertNotNull(benificiaryDetails.getHealthID()); + assertNotNull(benificiaryDetails.getHealthIDNumber()); + assertNotNull(benificiaryDetails.getFamilyId()); + assertNotNull(benificiaryDetails.getIdentity()); + assertEquals(expResp, beneficiaryRegistrationController.searchUserByID(request, httpRequest)); + assertEquals(expResp1, beneficiaryRegistrationController.searchUserByID(request, httpRequest)); + assertEquals(expResp2, beneficiaryRegistrationController.searchUserByID(request, httpRequest)); + assertEquals(expResp3, beneficiaryRegistrationController.searchUserByID(request, httpRequest)); + assertEquals(expResp4, beneficiaryRegistrationController.searchUserByID(request, httpRequest)); + assertEquals(expResp5, beneficiaryRegistrationController.searchUserByID(request, httpRequest)); + + } + + @Test + void testSearchUserByPhone() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + + BenPhoneMap benPhoneMap = new BenPhoneMap(); + benPhoneMap.setBenificiaryRegID(123L); + String request = benPhoneMap.toString(); + logger.info("Serach user by phone no request " + request); + JSONObject requestObj = new JSONObject(request); + int pageNumber = requestObj.has("pageNo") ? (requestObj.getInt("pageNo") - 1) : 0; + int rows = requestObj.has("rowsPerPage") ? requestObj.getInt("rowsPerPage") : 1000; + + String expResp = beneficiaryRegistrationController.searchUserByPhone(request, httpRequest); + + try { + response.setResponse(expResp); + } catch (Exception e) { + logger.error("serach user by phone NO failed with error " + e.getMessage(), e); + response.setError(e); + } + + Assertions.assertEquals(expResp, beneficiaryRegistrationController.searchUserByPhone(request, httpRequest)); + + } + + @Test + void testSearchBeneficiary() throws Exception { + OutputResponse output = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + BeneficiaryModel beneficiaryModel = new BeneficiaryModel(); + beneficiaryModel.setBeneficiaryID("Ben ID"); + beneficiaryModel.setBeneficiaryRegID(123L); + + String resp = beneficiaryModel.toString(); + + when(iemrSearchUserService.findBeneficiary(beneficiaryModel, auth)).thenReturn(resp); + String expResp = beneficiaryRegistrationController.searchBeneficiary(beneficiaryModel, httpRequest); + + try { + output.setResponse(resp); + } catch (Exception e) { + logger.error("searchBeneficiary failed with error " + e.getMessage(), e); + output.setError(e); + } + + Assertions.assertEquals(expResp, + beneficiaryRegistrationController.searchBeneficiary(beneficiaryModel, httpRequest)); + + } + + @Test + void testGetRegistrationData() { + OutputResponse response = new OutputResponse(); + BeneficiaryRegistrationData beneficiaryRegistrationData = new BeneficiaryRegistrationData(); + Status status = new Status(); + status.setDeleted(false); + List statusList = new ArrayList(); + statusList.add(status); + beneficiaryRegistrationData.setM_Status(statusList); + Title title = new Title(); + title.setDeleted(false); + List titleList = new ArrayList<Title>(); + titleList.add(title); + beneficiaryRegistrationData.setM_Title(titleList); + List<BeneficiaryEducation> beneficiaryEducationList = new ArrayList<BeneficiaryEducation>(); + beneficiaryRegistrationData.setI_BeneficiaryEducation(beneficiaryEducationList); + States states = new States(); + states.setDeleted(false); + List<States> statesList = new ArrayList<States>(); + statesList.add(states); + beneficiaryRegistrationData.setStates(statesList); + Gender gender = new Gender(); + gender.setCreatedBy("dona"); + List<Gender> genderList = new ArrayList<Gender>(); + genderList.add(gender); + beneficiaryRegistrationData.setM_genders(genderList); + MaritalStatus maritalStatus = new MaritalStatus(); + maritalStatus.setCreatedBy("dona"); + List<MaritalStatus> maritalStatusList = new ArrayList<MaritalStatus>(); + maritalStatusList.add(maritalStatus); + beneficiaryRegistrationData.setM_maritalStatuses(maritalStatusList); + Community community = new Community(); + community.setDeleted(false); + List<Community> communityList = new ArrayList<Community>(); + communityList.add(community); + beneficiaryRegistrationData.setM_communities(communityList); + Language language = new Language(); + language.setCreatedBy("dona"); + List<Language> languageList = new ArrayList<Language>(); + languageList.add(language); + beneficiaryRegistrationData.setM_language(languageList); + List<Directory> directoryList = new ArrayList<Directory>(); + beneficiaryRegistrationData.setDirectory(directoryList); + SexualOrientation sexualOrientation = new SexualOrientation(); + sexualOrientation.setDeleted(false); + List<SexualOrientation> sexualOrientationList = new ArrayList<SexualOrientation>(); + sexualOrientationList.add(sexualOrientation); + beneficiaryRegistrationData.setSexualOrientations(sexualOrientationList); + BenRelationshipType benRelationshipType = new BenRelationshipType(); + benRelationshipType.setDeleted(false); + List<BenRelationshipType> benRelationshipTypeList = new ArrayList<BenRelationshipType>(); + benRelationshipTypeList.add(benRelationshipType); + beneficiaryRegistrationData.setBenRelationshipTypes(benRelationshipTypeList); + BeneficiaryOccupation beneficiaryOccupation = new BeneficiaryOccupation(); + beneficiaryOccupation.setDeleted(false); + List<BeneficiaryOccupation> beneficiaryOccupationList = new ArrayList<BeneficiaryOccupation>(); + beneficiaryOccupationList.add(beneficiaryOccupation); + beneficiaryRegistrationData.setBeneficiaryOccupations(beneficiaryOccupationList); + GovtIdentityType govtIdentityType = new GovtIdentityType(); + govtIdentityType.setDeleted(false); + List<GovtIdentityType> govtIdentityTypeList = new ArrayList<GovtIdentityType>(); + govtIdentityTypeList.add(govtIdentityType); + beneficiaryRegistrationData.setGovtIdentityTypes(govtIdentityTypeList); + + String expResp = beneficiaryRegistrationController.getRegistrationData(); + + try { + response.setResponse(expResp); + } catch (Exception e) { + response.setError(e); + logger.error("get user registration data failed with error " + e.getMessage(), e); + } + + Assertions.assertEquals(expResp, beneficiaryRegistrationController.getRegistrationData()); + } + + @Test + void testUpdateBenefciary() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + BeneficiaryModel benificiaryDetails = new BeneficiaryModel(); + benificiaryDetails.setBeneficiaryID("Ben Id"); + benificiaryDetails.setBeneficiaryRegID(123L); + benificiaryDetails.setIs1097(true); + String resp = benificiaryDetails.toString(); + Integer updateCount = 1; + List<BeneficiaryModel> beneficiaryModelList = new ArrayList<BeneficiaryModel>(); + beneficiaryModelList.add(benificiaryDetails); + + String expResp = beneficiaryRegistrationController.updateBenefciary(resp, httpRequest); + try { + response.setResponse(expResp); + } catch (Exception e) { + logger.error("Update beneficiary failed with error " + e.getMessage(), e); + response.setError(e); + } + + assertNotEquals(0, updateCount); + Assertions.assertEquals(expResp, beneficiaryRegistrationController.updateBenefciary(resp, httpRequest)); + + } + + @Test + void testGetBeneficiariesByPhone() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + BenPhoneMap benPhoneMap = new BenPhoneMap(); + benPhoneMap.setBenificiaryRegID(123L); + String request = benPhoneMap.toString(); + logger.info("getBeneficiariesByPhoneNo request " + request); + int pageNumber = 0; + int rows = 1000; + String expResp = beneficiaryRegistrationController.getBeneficiariesByPhone(request, httpRequest); + + try { + response.setResponse(expResp); + } catch (Exception e) { + response.setError(e); + logger.error("getBeneficiariesByPhoneNo failed with error " + e.getMessage(), e); + } + + Assertions.assertEquals(expResp, + beneficiaryRegistrationController.getBeneficiariesByPhone(request, httpRequest)); + } + + @Test + void testUpdateBenefciaryCommunityorEducation() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + BeneficiaryModel benificiaryDetails = new BeneficiaryModel(); + benificiaryDetails.setBeneficiaryID("Ben Id"); + Integer updateCount = 1; + + String expResp = beneficiaryRegistrationController.updateBenefciaryCommunityorEducation(auth, httpRequest); + + try { + response.setResponse(expResp); + } catch (Exception e) { + logger.error("Update beneficiary failed with error " + e.getMessage(), e); + response.setError(e); + } + + assertNotEquals(0, updateCount); + Assertions.assertEquals(expResp, + beneficiaryRegistrationController.updateBenefciaryCommunityorEducation(auth, httpRequest)); + } + + @Test + void testGetBeneficiaryIDs() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + Integer benIDRequired = 123; + Integer vanID = 342; + Integer req = Integer.valueOf((benIDRequired) + (vanID)); + String request = req.toString(); + logger.info("generateBeneficiaryIDs request " + request); + + when(registerBenificiaryService.generateBeneficiaryIDs(request, httpRequest)).thenReturn(request); + String expResp = beneficiaryRegistrationController.getBeneficiaryIDs(request, httpRequest); + + try { + response.setResponse(expResp); + } catch (Exception e) { + logger.error(e.getMessage()); + response.setError(e); + } + + Assertions.assertEquals(expResp, beneficiaryRegistrationController.getBeneficiaryIDs(request, httpRequest)); } } diff --git a/src/test/java/com/iemr/common/controller/brd/BRDIntegrationControllerTest.java b/src/test/java/com/iemr/common/controller/brd/BRDIntegrationControllerTest.java new file mode 100644 index 00000000..bf453733 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/brd/BRDIntegrationControllerTest.java @@ -0,0 +1,59 @@ +package com.iemr.common.controller.brd; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.service.brd.BRDIntegrationService; + +@ExtendWith(MockitoExtension.class) +class BRDIntegrationControllerTest { + + @Mock + private BRDIntegrationService integrationService; + + @InjectMocks + private BRDIntegrationController controller; + + @Test + void getDetailsSuccess() throws Exception { + // Arrange + String request = new JSONObject().put("startDate", "2021-01-01").put("endDate", "2021-01-31").toString(); + String expectedResponse = "Expected BRD Data"; + when(integrationService.getData(anyString(), anyString())).thenReturn(expectedResponse); + + // Act + String actualResponse = controller.getDetails(request); + + // Assert + assertNotNull(actualResponse); + assertTrue(actualResponse.contains(expectedResponse)); + + // Verify that the integration service is called once with any strings + verify(integrationService).getData(anyString(), anyString()); + } + + @Test + void getDetailsFailure() { + // Arrange + String request = "invalid JSON"; + + // Act + String actualResponse = controller.getDetails(request); + + // Assert + assertNotNull(actualResponse); + assertTrue(actualResponse.contains("Unable to get BRD data")); + + } + +} diff --git a/src/test/java/com/iemr/common/controller/callhandling/CallControllerTest.java b/src/test/java/com/iemr/common/controller/callhandling/CallControllerTest.java new file mode 100644 index 00000000..4c9f970a --- /dev/null +++ b/src/test/java/com/iemr/common/controller/callhandling/CallControllerTest.java @@ -0,0 +1,667 @@ +package com.iemr.common.controller.callhandling; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.FileNotFoundException; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.common.data.beneficiary.BenOutboundCallAllocation; +import com.iemr.common.data.callhandling.BeneficiaryCall; +import com.iemr.common.data.callhandling.CallType; +import com.iemr.common.data.callhandling.OutboundCallRequest; +import com.iemr.common.data.callhandling.PhoneBlock; +import com.iemr.common.data.users.ProviderServiceMapping; +import com.iemr.common.model.beneficiary.BeneficiaryCallModel; +import com.iemr.common.model.beneficiary.CallRequestByIDModel; +import com.iemr.common.service.callhandling.BeneficiaryCallService; +import com.iemr.common.service.callhandling.CalltypeServiceImpl; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.redis.RedisSessionException; +import com.iemr.common.utils.response.OutputResponse; +import com.iemr.common.utils.sessionobject.SessionObject; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class CallControllerTest { + + public static final int CODE_EXCEPTION = 5005; + + @InjectMocks + CallController callController; + + InputMapper inputMapper = new InputMapper(); + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + private static final String XFORWARDEDFOR = "X-FORWARDED-FOR"; + private static final String AUTHORIZATION = "authorization"; + @Mock + private CalltypeServiceImpl calltypeServiceImpl; + @Mock + private BeneficiaryCallService beneficiaryCallService; + @Mock + private SessionObject s; + + @Test + void testGetAllCallTypes() throws IEMRException { + OutputResponse response = new OutputResponse(); + CallType callType = new CallType(); + callType.setProviderServiceMapID(123); + callType.setIsInbound(true); + callType.setIsOutbound(false); + List<CallType> callTypeList = new ArrayList<CallType>(); + callTypeList.add(callType); + List<CallType> mCalltypes = callTypeList; + String providerDetails = callType.toString(); + + when(calltypeServiceImpl.getAllCalltypes(providerDetails)).thenReturn(mCalltypes); + + String expResp = callController.getAllCallTypes(providerDetails); + + Assertions.assertEquals(expResp, callController.getAllCallTypes(providerDetails)); + + } + + @Test + void testGetAllCallTypes_CatchBlock() throws IEMRException { + String providerDetails = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(calltypeServiceImpl.getAllCalltypes(providerDetails)).thenThrow(NotFoundException.class); + String response = callController.getAllCallTypes(providerDetails); + Assertions.assertEquals(response, callController.getAllCallTypes(providerDetails)); + } + + @Test + void testGetCallTypesV1() throws JSONException, IEMRException, JsonMappingException, JsonProcessingException { + String providerDetails = "{\"providerServiceMapID\":\"1 - provider service ID\", \"isInbound\": Optional boolean," + + "\"isOutbound\": Optional boolean}"; + + OutputResponse response = new OutputResponse(); + + String mCalltypes = "test"; + + when(calltypeServiceImpl.getAllCalltypesV1(providerDetails)).thenReturn(mCalltypes); + + response.setResponse(mCalltypes); + + String expRes = callController.getCallTypesV1(providerDetails); + + assertEquals(expRes, callController.getCallTypesV1(providerDetails)); + } + + @Test + void testGetCallTypesV1_Exception() + throws JSONException, IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(calltypeServiceImpl.getAllCalltypesV1(request)).thenThrow(NotFoundException.class); + + String response = callController.getCallTypesV1(request); + assertEquals(response, callController.getCallTypesV1(request)); + } + + @Test + void testStartCall() throws IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + BeneficiaryCall beneficiaryCall = new BeneficiaryCall(); + beneficiaryCall.setCalledServiceID(123); + beneficiaryCall.setCallID("avc"); + beneficiaryCall.setIs1097(true); + beneficiaryCall.setCreatedBy("bbb"); + beneficiaryCall.setAgentID("agent id"); + beneficiaryCall.setIsOutbound(true); + beneficiaryCall.setIsCalledEarlier(true); + beneficiaryCall.setReceivedRoleName("MO"); + String request = beneficiaryCall.toString(); + HttpServletRequest fromRequest = mock(HttpServletRequest.class); + + String remoteAddress = fromRequest.getHeader(XFORWARDEDFOR); + when(beneficiaryCallService.createCall(request, remoteAddress)).thenReturn(beneficiaryCall); + + String expResp = callController.startCall(request, fromRequest); + + assertTrue(remoteAddress == null || remoteAddress.trim().length() == 0); + Assertions.assertEquals(expResp, callController.startCall(request, fromRequest)); + } + + @Test + void testStartCall_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest fromRequest = mock(HttpServletRequest.class); + String remoteAddress = fromRequest.getHeader(XFORWARDEDFOR); + when(beneficiaryCallService.createCall(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = callController.startCall(request, fromRequest); + Assertions.assertEquals(response, callController.startCall(request, fromRequest)); + } + + @Test + void testUpdateBeneficiaryIDInCall() + throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + + OutputResponse response = new OutputResponse(); + String isCalledEarlier = String.valueOf(false); + String benCallID = String.valueOf(123); + String beneficiaryRegID = String.valueOf(543); + String request = "{\"benCallID\":" + benCallID + "," + "\"isCalledEarlier\":\"" + isCalledEarlier + "\"," + + "\"beneficiaryRegID\":" + beneficiaryRegID + "}"; + + JSONObject requestObject = new JSONObject(request); + Integer beneficiaryId = 123; + when(beneficiaryCallService.updateBeneficiaryIDInCall(request)).thenReturn(beneficiaryId); + requestObject.put("updatedCount", beneficiaryId); + + String expResp = callController.updateBeneficiaryIDInCall(request); + + Assertions.assertEquals(expResp, callController.updateBeneficiaryIDInCall(request)); + } + + @Test + void testUpdateBeneficiaryIDInCall_CatchBlock() + throws JSONException, IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.updateBeneficiaryIDInCall(request)).thenThrow(RuntimeException.class); + String response = callController.updateBeneficiaryIDInCall(request); + Assertions.assertEquals(response, callController.updateBeneficiaryIDInCall(request)); + } + + @Test + void testUpdateBeneficiaryIDInCall_CatchBlockJson() + throws JSONException, IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + JSONObject jsonObject = new JSONObject(request); + JSONObject json = Mockito.mock(JSONObject.class); + when(beneficiaryCallService.updateBeneficiaryIDInCall(Mockito.any())).thenReturn(123); + String response = callController.updateBeneficiaryIDInCall(request); + Assertions.assertTrue(response.contains("e")); + } + + @Test + void testCloseCall() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + BeneficiaryCallModel beneficiaryCall = new BeneficiaryCallModel(); + beneficiaryCall.setBenCallID(123L); + beneficiaryCall.setRemarks("remarks"); + beneficiaryCall.setCallClosureType("valid"); + beneficiaryCall.setCallTypeID(123); + beneficiaryCall.setEndCall(true); + beneficiaryCall.setFitToBlock(false); + beneficiaryCall.setBeneficiaryRegID(342L); + beneficiaryCall.setEmergencyType((short) 12); + beneficiaryCall.setAgentIPAddress("abc"); + beneficiaryCall.setAgentID("bvcf"); + beneficiaryCall.setIsOutbound(true); + Integer updateCount = 0; + + String request = new ObjectMapper().writeValueAsString(beneficiaryCall); + logger.info("closeCallReqObj " + request); + String remoteAddress = httpRequest.getHeader(XFORWARDEDFOR); + when(httpRequest.getHeader(XFORWARDEDFOR)).thenReturn(null); + + String expResp = callController.closeCall(request, httpRequest); + + assertTrue(remoteAddress == null || remoteAddress.trim().length() == 0); + Assertions.assertEquals(expResp, callController.closeCall(request, httpRequest)); + } + + @Test + void testCloseCall_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String remoteAddress = httpRequest.getHeader(XFORWARDEDFOR); + when(beneficiaryCallService.closeCall(request, remoteAddress)).thenThrow(FileNotFoundException.class); + String response = callController.closeCall(request, httpRequest); + Assertions.assertEquals(response, callController.closeCall(request, httpRequest)); + } + + @Test + void testOutboundCallList() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + OutboundCallRequest outboundCallRequest = new OutboundCallRequest(); + outboundCallRequest.setProviderServiceMapID(123); + outboundCallRequest.setAssignedUserID(123); + outboundCallRequest.setRequestedServiceID(43); + outboundCallRequest.setPreferredLanguageName("English"); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.outboundCallList(request, auth)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.outboundCallList(request, httpRequest)); + + } + + @Test + void testOutboundCallList_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + when(beneficiaryCallService.outboundCallList(request, auth)).thenThrow(RuntimeException.class); + String response = callController.outboundCallList(request, httpRequest); + Assertions.assertEquals(response, callController.outboundCallList(request, httpRequest)); + } + + @Test + void testOutboundCallCount() throws Exception, JSONException { + OutputResponse response = new OutputResponse(); + OutboundCallRequest outboundCallRequest = new OutboundCallRequest(); + outboundCallRequest.setPreferredLanguageName("English"); + outboundCallRequest.setProviderServiceMapID(123); + outboundCallRequest.setAssignedUserID(123); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.outboundCallCount(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.outboundCallCount(request)); + } + + @Test + void testOutboundCallCount_CatchBlock() throws Exception, JSONException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.outboundCallCount(request)).thenThrow(RuntimeException.class); + String response = callController.outboundCallCount(request); + Assertions.assertEquals(response, callController.outboundCallCount(request)); + } + + @Test + void testFilterCallList() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + BeneficiaryCall beneficiaryCall = new BeneficiaryCall(); + beneficiaryCall.setCalledServiceID(123); + beneficiaryCall.setCallTypeID(23); + beneficiaryCall.setFilterStartDate(Timestamp.from(Instant.now())); + beneficiaryCall.setFilterEndDate(Timestamp.from(Instant.now())); + beneficiaryCall.setReceivedRoleName("MO"); + beneficiaryCall.setPhoneNo("8617577134"); + beneficiaryCall.setAgentID("5435"); + beneficiaryCall.setInboundOutbound("inbound"); + beneficiaryCall.setIs1097(false); + String request = beneficiaryCall.toString(); + when(beneficiaryCallService.filterCallList(request, auth)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.filterCallList(request, httpRequest)); + } + + @Test + void testFilterCallList_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + when(beneficiaryCallService.filterCallList(request, auth)).thenThrow(RuntimeException.class); + String response = callController.filterCallList(request, httpRequest); + Assertions.assertEquals(response, callController.filterCallList(request, httpRequest)); + } + + @Test + void testFilterCallListPaginated() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + BeneficiaryCall beneficiaryCall = new BeneficiaryCall(); + beneficiaryCall.setCalledServiceID(123); + beneficiaryCall.setCallTypeID(23); + beneficiaryCall.setFilterStartDate(Timestamp.from(Instant.now())); + beneficiaryCall.setFilterEndDate(Timestamp.from(Instant.now())); + beneficiaryCall.setReceivedRoleName("MO"); + beneficiaryCall.setPhoneNo("8617577134"); + beneficiaryCall.setAgentID("5435"); + beneficiaryCall.setInboundOutbound("inbound"); + beneficiaryCall.setIs1097(false); + beneficiaryCall.setPageNo(4); + beneficiaryCall.setPageSize(12); + String request = beneficiaryCall.toString(); + when(beneficiaryCallService.filterCallListWithPagination(request, auth)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.filterCallListPaginated(request, httpRequest)); + } + + @Test + void testFilterCallListPaginated_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest httpRequest = mock(HttpServletRequest.class); + String auth = httpRequest.getHeader(AUTHORIZATION); + when(beneficiaryCallService.filterCallListWithPagination(request, auth)).thenThrow(RuntimeException.class); + String response = callController.filterCallListPaginated(request, httpRequest); + Assertions.assertEquals(response, callController.filterCallListPaginated(request, httpRequest)); + } + + @Test + void testOutboundAllocation() throws IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + BenOutboundCallAllocation benOutboundCallAllocation = new BenOutboundCallAllocation(); + List<Integer> userID = new ArrayList<Integer>(); + userID.add(123); + OutboundCallRequest[] outboundCallRequests = new OutboundCallRequest[2]; + benOutboundCallAllocation.setUserID(userID); + benOutboundCallAllocation.setAllocateNo(123); + benOutboundCallAllocation.setOutboundCallRequests(outboundCallRequests); + String request = benOutboundCallAllocation.toString(); + when(beneficiaryCallService.outboundAllocation(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.outboundAllocation(request)); + } + + @Test + void testOutboundAllocation_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.outboundAllocation(request)).thenThrow(RuntimeException.class); + String response = callController.outboundAllocation(request); + Assertions.assertEquals(response, callController.outboundAllocation(request)); + } + + @Test + void testCompleteOutboundCall() throws Exception { + OutputResponse response = new OutputResponse(); + OutboundCallRequest outboundCallRequest = new OutboundCallRequest(); + outboundCallRequest.setOutboundCallReqID(23L); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setRequestedFor("gfd"); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.completeOutboundCall(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.completeOutboundCall(request)); + } + + @Test + void testCompleteOutboundCall_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.completeOutboundCall(request)).thenThrow(RuntimeException.class); + String response = callController.completeOutboundCall(request); + Assertions.assertEquals(response, callController.completeOutboundCall(request)); + } + + @Test + void testUpdateOutboundCall() throws Exception { + OutputResponse response = new OutputResponse(); + OutboundCallRequest outboundCallRequest = new OutboundCallRequest(); + outboundCallRequest.setOutboundCallReqID(23L); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setRequestedFor("gfd"); + outboundCallRequest.setRequestedFor("requested"); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.updateOutboundCall(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.updateOutboundCall(request)); + } + + @Test + void testUpdateOutboundCall_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.updateOutboundCall(request)).thenThrow(RuntimeException.class); + String response = callController.updateOutboundCall(request); + Assertions.assertEquals(response, callController.updateOutboundCall(request)); + } + + @Test + void testResetOutboundCall() throws Exception { + OutputResponse response = new OutputResponse(); + OutboundCallRequest outboundCallRequest = new OutboundCallRequest(); + List<Long> outboundCallReqIDs = new ArrayList<Long>(); + outboundCallReqIDs.add(123L); + outboundCallRequest.setOutboundCallReqIDs(outboundCallReqIDs); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.resetOutboundCall(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.resetOutboundCall(request)); + } + + @Test + void testResetOutboundCall_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.resetOutboundCall(request)).thenThrow(RuntimeException.class); + String response = callController.resetOutboundCall(request); + Assertions.assertEquals(response, callController.resetOutboundCall(request)); + } + + @Test + void testGetBlacklistNumbers() throws IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + PhoneBlock phoneBlock = new PhoneBlock(); + phoneBlock.setProviderServiceMapID(123); + phoneBlock.setPhoneNo("8617577134"); + phoneBlock.setIsBlocked(false); + String request = phoneBlock.toString(); + + when(beneficiaryCallService.getBlacklistNumbers(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.getBlacklistNumbers(request)); + } + + @Test + void testGetBlacklistNumbers_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.getBlacklistNumbers(request)).thenThrow(NotFoundException.class); + String response = callController.getBlacklistNumbers(request); + Assertions.assertEquals(response, callController.getBlacklistNumbers(request)); + } + + @Test + void testBlockPhoneNumber() throws IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + PhoneBlock phoneBlock = new PhoneBlock(); + phoneBlock.setPhoneBlockID(123L); + String request = phoneBlock.toString(); + when(beneficiaryCallService.blockPhoneNumber(request)).thenReturn(response); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.blockPhoneNumber(request)); + } + + @Test + void testBlockPhoneNumber_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.blockPhoneNumber(request)).thenThrow(NotFoundException.class); + String response = callController.blockPhoneNumber(request); + Assertions.assertEquals(response, callController.blockPhoneNumber(request)); + } + + @Test + void testUnblockPhoneNumber() throws IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + PhoneBlock phoneBlock = new PhoneBlock(); + phoneBlock.setPhoneBlockID(123L); + String request = phoneBlock.toString(); + when(beneficiaryCallService.unblockPhoneNumber(request)).thenReturn(response); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.unblockPhoneNumber(request)); + } + + @Test + void testUnblockPhoneNumber_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.unblockPhoneNumber(request)).thenThrow(NotFoundException.class); + String response = callController.unblockPhoneNumber(request); + Assertions.assertEquals(response, callController.unblockPhoneNumber(request)); + } + + @Test + void testUpdateBeneficiaryCallCDIStatus() throws Exception { + OutputResponse response = new OutputResponse(); + BeneficiaryCall beneficiaryCall = new BeneficiaryCall(); + beneficiaryCall.setBenCallID(123L); + beneficiaryCall.setCDICallStatus("status"); + String request = beneficiaryCall.toString(); + JSONObject requestObject = new JSONObject(request); + Integer benCallId = 123; + when(beneficiaryCallService.updateBeneficiaryCallCDIStatus(request)).thenReturn(benCallId); + requestObject.put("updatedCount", benCallId); + String expResp = callController.updateBeneficiaryCallCDIStatus(request); + Assertions.assertEquals(expResp, callController.updateBeneficiaryCallCDIStatus(request)); + } + + @Test + void testUpdateBeneficiaryCallCDIStatus_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.updateBeneficiaryCallCDIStatus(request)).thenThrow(NotFoundException.class); + String response = callController.updateBeneficiaryCallCDIStatus(request); + Assertions.assertEquals(response, callController.updateBeneficiaryCallCDIStatus(request)); + } + + @Test + void testGetCallHistoryByCallID_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.getCallHistoryByCallID(request)).thenThrow(NotFoundException.class); + String response = callController.getCallHistoryByCallID(request); + Assertions.assertEquals(response, callController.getCallHistoryByCallID(request)); + } + + @Test + void testOutboundCallListByCallID() throws IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + BeneficiaryCall beneficiaryCall = new BeneficiaryCall(); + beneficiaryCall.setServicesProvided("abc"); + beneficiaryCall.setCallID("call id"); + String request = beneficiaryCall.toString(); + when(beneficiaryCallService.outboundCallListByCallID(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.outboundCallListByCallID(request)); + } + + @Test + void testOutboundCallListByCallID_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.outboundCallListByCallID(request)).thenThrow(NotFoundException.class); + String response = callController.outboundCallListByCallID(request); + Assertions.assertEquals(response, callController.outboundCallListByCallID(request)); + } + + @Test + void testNueisanceCallHistory() throws IEMRException, Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String auth = serverRequest.getHeader(AUTHORIZATION); + BeneficiaryCall beneficiaryCall = new BeneficiaryCall(); + beneficiaryCall.setCalledServiceID(123); + beneficiaryCall.setPhoneNo("8617577134"); + beneficiaryCall.setCount(3); + String request = beneficiaryCall.toString(); + when(beneficiaryCallService.nueisanceCallHistory(request, auth)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), callController.nueisanceCallHistory(request, serverRequest)); + + } + + @Test + void testNueisanceCallHistory_CatchBlock() throws IEMRException, Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String auth = serverRequest.getHeader(AUTHORIZATION); + when(beneficiaryCallService.nueisanceCallHistory(request, auth)).thenThrow(NotFoundException.class); + String response = callController.nueisanceCallHistory(request, serverRequest); + Assertions.assertEquals(response, callController.nueisanceCallHistory(request, serverRequest)); + } + + @Test + void testBeneficiaryByCallID_CatchBlock() throws IEMRException, Exception, JsonProcessingException { + String expRequest = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + CallRequestByIDModel request = new CallRequestByIDModel(); + request.setCallID(expRequest); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(beneficiaryCallService.beneficiaryByCallID(request, serverRequest.getHeader("Authorization"))) + .thenThrow(NotFoundException.class); + String response = callController.beneficiaryByCallID(request, serverRequest); + Assertions.assertEquals(response, callController.beneficiaryByCallID(request, serverRequest)); + } + + @Test + void testGetFilePathCTI() throws IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + BeneficiaryCall beneficiaryCall = new BeneficiaryCall(); + beneficiaryCall.setAgentID("agent id"); + beneficiaryCall.setCallID("call id"); + String request = beneficiaryCall.toString(); + when(beneficiaryCallService.cTIFilePathNew(request)).thenReturn(request); + response.setResponse(request.toString()); + String expResp = callController.getFilePathCTI(request); + assertNotNull(expResp); + Assertions.assertEquals(response.toString(), callController.getFilePathCTI(request)); + } + + @Test + void testGetFilePathCTI_NotNull() throws IEMRException { + OutputResponse response = new OutputResponse(); + String pathResponse = null; + response.setError(5000, "File path not available"); + assertNull(pathResponse); + assertTrue(response.toString().contains("File path not available")); + } + + @Test + void testGetFilePathCTI_CatchBlock() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.cTIFilePathNew(request)).thenThrow(NotFoundException.class); + String response = callController.getFilePathCTI(request); + Assertions.assertEquals(response, callController.getFilePathCTI(request)); + } + + @Test + void testRedisInsert() throws RedisSessionException { + String request = "test"; + OutputResponse response = new OutputResponse(); + + String key = "123"; + + when(s.setSessionObject("1277.1000", "12345")).thenReturn(key); + response.setResponse(key); + + String expRes = callController.redisInsert(request); + + assertEquals(expRes, callController.redisInsert(request)); + } + + @Test + void testRedisInsert_Exception() throws RedisSessionException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(s.setSessionObject("1277.1000", "12345")).thenThrow(NotFoundException.class); + + String response = callController.redisInsert(request); + assertEquals(response, callController.redisInsert(request)); + } + + @Test + void redisFetch() throws JSONException, RedisSessionException { + String request = "{\"sessionID\":\"123\"}"; + OutputResponse response = new OutputResponse(); + JSONObject obj = new JSONObject(request); + + String value = "test"; + when(s.getSessionObject(obj.getString("sessionID"))).thenReturn(value); + response.setResponse(value); + + String expRes = callController.redisFetch(request); + + assertTrue(obj.has("sessionID")); + assertEquals(expRes, callController.redisFetch(request)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/carestream/CareStreamCreateOrderControllerTest.java b/src/test/java/com/iemr/common/controller/carestream/CareStreamCreateOrderControllerTest.java new file mode 100644 index 00000000..ab92d06b --- /dev/null +++ b/src/test/java/com/iemr/common/controller/carestream/CareStreamCreateOrderControllerTest.java @@ -0,0 +1,68 @@ +package com.iemr.common.controller.carestream; + +import static org.mockito.Mockito.*; + +import java.io.IOException; +import java.net.UnknownHostException; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.controller.carestream.CareStreamCreateOrderController; +import com.iemr.common.data.carestream.CreateOrderData; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +@ExtendWith(MockitoExtension.class) +public class CareStreamCreateOrderControllerTest { + + @Mock + private InputMapper inputMapper; + + @InjectMocks + private CareStreamCreateOrderController careStreamCreateOrderController; + + @Test + void createOrderTest() throws UnknownHostException, IOException { + String createOrder = "{\n" + " \"firstName\": \"John\",\n" + " \"middleName\": \"Doe\",\n" + + " \"LastName\": \"Smith\",\n" + " \"gender\": \"Male\",\n" + " \"dob\": \"1980-01-01\",\n" + + " \"patientID\": \"123456789\",\n" + " \"acc\": \"ACC1234\"\n" + "}"; + + CreateOrderData benificiaryDetails = InputMapper.gson().fromJson(createOrder, CreateOrderData.class); + + String response = careStreamCreateOrderController.createOrder(createOrder); + + assertTrue(response.contains("Failed with Cannot assign")); + } + + @Test + void updateOrderTest() throws UnknownHostException, IOException { + String updateOrder = "{\n" + " \"firstName\": \"John\",\n" + " \"middleName\": \"Doe\",\n" + + " \"LastName\": \"Smith\",\n" + " \"gender\": \"Male\",\n" + " \"dob\": \"1980-01-01\",\n" + + " \"patientID\": \"123456789\",\n" + " \"acc\": \"ACC1234\"\n" + "}"; + + CreateOrderData benificiaryDetails = InputMapper.gson().fromJson(updateOrder, CreateOrderData.class); + + String response = careStreamCreateOrderController.updateOrder(updateOrder); + + assertTrue(response.contains("Connection timed out")); + } + + @Test + void deleteOrderTest() throws UnknownHostException, IOException { + String deleteOrder = "{\n" + " \"firstName\": \"John\",\n" + " \"middleName\": \"Doe\",\n" + + " \"LastName\": \"Smith\",\n" + " \"gender\": \"Male\",\n" + " \"dob\": \"1980-01-01\",\n" + + " \"patientID\": \"123456789\",\n" + " \"acc\": \"ACC1234\"\n" + "}"; + + CreateOrderData benificiaryDetails = InputMapper.gson().fromJson(deleteOrder, CreateOrderData.class); + + String response = careStreamCreateOrderController.deleteOrder(deleteOrder); + assertTrue(response.contains("Failed with connection issues")); + + } +} \ No newline at end of file diff --git a/src/test/java/com/iemr/common/controller/cti/ComputerTelephonyIntegrationControllerTest.java b/src/test/java/com/iemr/common/controller/cti/ComputerTelephonyIntegrationControllerTest.java new file mode 100644 index 00000000..ac1cd0d6 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/cti/ComputerTelephonyIntegrationControllerTest.java @@ -0,0 +1,626 @@ +package com.iemr.common.controller.cti; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.when; + +import org.json.JSONException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.iemr.common.data.cti.AgentLoginKey; +import com.iemr.common.data.cti.AgentSkills; +import com.iemr.common.data.cti.AgentState; +import com.iemr.common.data.cti.CTICampaigns; +import com.iemr.common.data.cti.CTIUser; +import com.iemr.common.data.cti.CTIVoiceFile; +import com.iemr.common.data.cti.CallBeneficiary; +import com.iemr.common.data.cti.CallDisposition; +import com.iemr.common.data.cti.CampaignNames; +import com.iemr.common.data.cti.CampaignRole; +import com.iemr.common.data.cti.CampaignSkills; +import com.iemr.common.data.cti.CustomerLanguage; +import com.iemr.common.data.cti.TransferCall; +import com.iemr.common.service.cti.CTIService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.NotFoundException; +@ExtendWith(MockitoExtension.class) +class ComputerTelephonyIntegrationControllerTest { + + @InjectMocks + ComputerTelephonyIntegrationController computerTelephonyIntegrationController; + + @Mock + CTIService ctiService; + InputMapper inputMapper = new InputMapper(); + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + + + @Test + void testGetCampaignSkills() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + CampaignSkills campaign = new CampaignSkills(); + campaign.setCampaign_name("name"); + String request = campaign.toString(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(null); + when(ctiService.getCampaignSkills(request, null)).thenReturn(response); + response.setResponse(request.toString()); + reset(serverRequest); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(""); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getCampaignSkills(request, serverRequest)); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getCampaignSkills(request, serverRequest)); + } + + @Test + void testGetCampaignSkills_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getCampaignSkills(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getCampaignSkills(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getCampaignSkills(request, serverRequest)); + } + + @Test + void testGetAgentState() throws JSONException, IEMRException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(null); + AgentState agentState = new AgentState(); + agentState.setAgent_id("agent id"); + String request = agentState.toString(); + when(ctiService.getAgentState(request, null)).thenReturn(response); + response.setResponse(request.toString()); + reset(serverRequest); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(""); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getAgentState(request, serverRequest)); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getAgentState(request, serverRequest)); + } + + @Test + void testGetAgentState_CatchBlock() throws JSONException, IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getAgentState(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getAgentState(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getAgentState(request, serverRequest)); + } + + @Test + void testGetAgentCallStats() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(null); + AgentState agentState = new AgentState(); + agentState.setAgent_id("agent id"); + String request = agentState.toString(); + when(ctiService.getAgentCallStats(request, null)).thenReturn(response); + response.setResponse(request.toString()); + reset(serverRequest); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(""); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getAgentCallStats(request, serverRequest)); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getAgentCallStats(request, serverRequest)); + } + + @Test + void testGetAgentCallStats_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getAgentCallStats(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getAgentCallStats(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getAgentCallStats(request, serverRequest)); + } + + @Test + void testGetCampaignNames() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(null); + CampaignNames names = new CampaignNames(); + names.setServiceName("service name"); + names.setType("type"); + String request = names.toString(); + when(ctiService.getCampaignNames(request, null)).thenReturn(response); + response.setResponse(request.toString()); + reset(serverRequest); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(""); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getCampaignNames(request, serverRequest)); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getCampaignNames(request, serverRequest)); + } + + @Test + void testGetCampaignNames_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException{ + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getCampaignNames(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getCampaignNames(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getCampaignNames(request, serverRequest)); + } + + @Test + void testGetLoginKey() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(null); + AgentLoginKey agentState = new AgentLoginKey(); + agentState.setUsername("username"); + agentState.setPassword("password"); + String request = agentState.toString(); + when(ctiService.getLoginKey(request, null)).thenReturn(response); + response.setResponse(request.toString()); + reset(serverRequest); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(""); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getLoginKey(request, serverRequest)); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getLoginKey(request, serverRequest)); + } + + @Test + void testGetLoginKey_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getLoginKey(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getLoginKey(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getLoginKey(request, serverRequest)); + } + + @Test + void testDoAgentLogout() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(null); + AgentState agentState = new AgentState(); + agentState.setAgent_id("agent id"); + String request = agentState.toString(); + when(ctiService.agentLogout(request, null)).thenReturn(response); + response.setResponse(request.toString()); + reset(serverRequest); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(""); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.doAgentLogout(request, serverRequest)); + } + + @Test + void testDoAgentLogout_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.agentLogout(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.doAgentLogout(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.doAgentLogout(request, serverRequest)); + } + + @Test + void testGetOnlineAgents() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + AgentState agentState = new AgentState(); + agentState.setAgent_id("agent id"); + String request = agentState.toString(); + when(ctiService.getOnlineAgents(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getOnlineAgents(request, serverRequest)); + } + + @Test + void testGetOnlineAgents_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getOnlineAgents(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getOnlineAgents(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getOnlineAgents(request, serverRequest)); + } + + @Test + void testCallBeneficiary() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(null); + CallBeneficiary agentState = new CallBeneficiary(); + agentState.setAgent_id("agent id"); + agentState.setPhone_num("ph no"); + String request = agentState.toString(); + when(ctiService.callBeneficiary(request, null)).thenReturn(response); + response.setResponse(request.toString()); + reset(serverRequest); + when(serverRequest.getHeader("X-FORWARDED-FOR")).thenReturn(""); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.callBeneficiary(request, serverRequest)); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.callBeneficiary(request, serverRequest)); + } + + @Test + void testCallBeneficiary_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.callBeneficiary(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.callBeneficiary(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.callBeneficiary(request, serverRequest)); + } + + @Test + void testAddUpdateUserData() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CTIUser state = new CTIUser(); + state.setUsername("username"); + state.setPassword("password"); + state.setFirstname("firstname"); + state.setLastname("last name"); + state.setPhone("phone"); + state.setEmail("email"); + state.setRole("role"); + state.setDesignation("designation"); + String request = state.toString(); + when(ctiService.addUpdateUserData(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.addUpdateUserData(request, serverRequest)); + } + + @Test + void testAddUpdateUserData_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.addUpdateUserData(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.addUpdateUserData(request, serverRequest); + assertTrue(response.contains("Failed with null")); + } + + @Test + void testGetTransferCampaigns() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CTICampaigns agentState = new CTICampaigns(); + agentState.setAgent_id("agent id"); + String request = agentState.toString(); + when(ctiService.getTransferCampaigns(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getTransferCampaigns(request, serverRequest)); + } + + @Test + void testGetTransferCampaigns_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getTransferCampaigns(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getTransferCampaigns(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getTransferCampaigns(request, serverRequest)); + } + + @Test + void testGetCampaignRoles() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CampaignRole campaign = new CampaignRole(); + campaign.setCampaign("campaign name"); + String request = campaign.toString(); + when(ctiService.getCampaignRoles(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getCampaignRoles(request, serverRequest)); + } + + @Test + void testGetCampaignRoles_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getCampaignRoles(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getCampaignRoles(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getCampaignRoles(request, serverRequest)); + } + + @Test + void testSetCallDisposition() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CallDisposition disposition = new CallDisposition(); + disposition.setAgent_id("agent id"); + disposition.setCust_disp("cust"); + disposition.setCategory("category"); + disposition.setSession_id("session id"); + String request = disposition.toString(); + when(ctiService.setCallDisposition(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.setCallDisposition(request, serverRequest)); + } + + @Test + void testSetCallDisposition_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.setCallDisposition(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.setCallDisposition(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.setCallDisposition(request, serverRequest)); + } + + @Test + void testCreateVoiceFile() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CTIVoiceFile disposition = new CTIVoiceFile(); + disposition.setAgent_id("agent id"); + disposition.setSession_id("session id"); + String request = disposition.toString(); + when(ctiService.createVoiceFile(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.createVoiceFile(request, serverRequest)); + } + + @Test + void testCreateVoiceFile_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.createVoiceFile(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.createVoiceFile(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.createVoiceFile(request, serverRequest)); + } + + @Test + void testGetVoiceFile() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CTIVoiceFile disposition = new CTIVoiceFile(); + disposition.setAgent_id("agent id"); + disposition.setSession_id("session id"); + String request = disposition.toString(); + when(ctiService.getVoiceFile(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getVoiceFile(request, serverRequest)); + } + + @Test + void testGetVoiceFile_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getVoiceFile(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getVoiceFile(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getVoiceFile(request, serverRequest)); + } + + @Test + void testDisconnectCall() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + AgentSkills agent = new AgentSkills(); + agent.setAgent_id("agent id"); + String request = agent.toString(); + when(ctiService.disconnectCall(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.disconnectCall(request, serverRequest)); + } + + @Test + void testDisconnectCall_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.disconnectCall(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.disconnectCall(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.disconnectCall(request, serverRequest)); + } + + @Test + void testSwitchToInbound() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CallBeneficiary agent = new CallBeneficiary(); + agent.setAgent_id("agent id"); + String request = agent.toString(); + when(ctiService.switchToInbound(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.switchToInbound(request, serverRequest)); + } + + @Test + void testSwitchToInbound_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.switchToInbound(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.switchToInbound(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.switchToInbound(request, serverRequest)); + } + + @Test + void testSwitchToOutbound() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CallBeneficiary agent = new CallBeneficiary(); + agent.setAgent_id("agent id"); + String request = agent.toString(); + when(ctiService.switchToOutbound(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.switchToOutbound(request, serverRequest)); + } + + @Test + void testSwitchToOutbound_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.switchToOutbound(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.switchToOutbound(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.switchToOutbound(request, serverRequest)); + } + + @Test + void testGetAgentIPAddress() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + AgentState agent = new AgentState(); + agent.setAgent_id("agent id"); + String request = agent.toString(); + when(ctiService.getAgentIPAddress(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getAgentIPAddress(request, serverRequest)); + } + + @Test + void testGetAgentIPAddress_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getAgentIPAddress(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getAgentIPAddress(request, serverRequest); + assertTrue(response.contains("Failed with null")); + } + + @Test + void testGetAvailableAgentSkills() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + AgentSkills agent = new AgentSkills(); + agent.setCampaign_name("name"); + agent.setSkill("skill"); + String request = agent.toString(); + when(ctiService.getAvailableAgentSkills(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getAvailableAgentSkills(request, serverRequest)); + } + + @Test + void testGetAvailableAgentSkills_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getAvailableAgentSkills(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getAvailableAgentSkills(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getAvailableAgentSkills(request, serverRequest)); + } + + @Test + void testTransferCall() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + TransferCall transferCall = new TransferCall(); + transferCall.setTransfer_from("transfer from"); + transferCall.setTransfer_to("transfer to"); + transferCall.setTransfer_campaign_info("info"); + transferCall.setSkill_transfer_flag("transfer flag"); + transferCall.setSkill("skill"); + transferCall.setBenCallID(123L); + transferCall.setAgentIPAddress("ip address"); + transferCall.setCallTypeID(123); + String request = transferCall.toString(); + when(ctiService.transferCall(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.transferCall(request, serverRequest)); + } + + @Test + void testTransferCall_CatchBlock() throws IEMRException, JSONException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.transferCall(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.transferCall(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.transferCall(request, serverRequest)); + } + + @Test + void testCustomerPreferredLanguage() throws JsonMappingException, JsonProcessingException { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CustomerLanguage custLang = new CustomerLanguage(); + custLang.setCust_ph_no("ph no"); + custLang.setCampaign_name("name"); + custLang.setLanguage("language"); + custLang.setAction("action"); + String request = custLang.toString(); + when(ctiService.customerPreferredLanguage(custLang, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.customerPreferredLanguage(request, serverRequest)); + } + + @Test + void testCustomerPreferredLanguage_CatchBlock() throws JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + CustomerLanguage custLang = new CustomerLanguage(); + custLang.setCust_ph_no("ph no"); + custLang.setCampaign_name("name"); + custLang.setLanguage("language"); + custLang.setAction("action"); + when(ctiService.customerPreferredLanguage(custLang, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.customerPreferredLanguage(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.customerPreferredLanguage(request, serverRequest)); + } + + @Test + void testGetIVRSPathDetails() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + AgentState zoneData = new AgentState(); + zoneData.setAgent_id("agent id"); + String request = zoneData.toString(); + when(ctiService.getIVRSPathDetails(request, remoteAddress)).thenReturn(response); + response.setResponse(request.toString()); + assertNull(remoteAddress); + Assertions.assertEquals(response.toString(), computerTelephonyIntegrationController.getIVRSPathDetails(request, serverRequest)); + } + + @Test + void testGetIVRSPathDetails_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String remoteAddress = serverRequest.getHeader("X-FORWARDED-FOR"); + when(ctiService.getIVRSPathDetails(request, remoteAddress)).thenThrow(NotFoundException.class); + String response = computerTelephonyIntegrationController.getIVRSPathDetails(request, serverRequest); + Assertions.assertEquals(response, computerTelephonyIntegrationController.getIVRSPathDetails(request, serverRequest)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/directory/DirectoryControllerTest.java b/src/test/java/com/iemr/common/controller/directory/DirectoryControllerTest.java new file mode 100644 index 00000000..d7efd0c1 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/directory/DirectoryControllerTest.java @@ -0,0 +1,126 @@ +package com.iemr.common.controller.directory; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +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 java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.iemr.common.data.directory.InstituteDirectoryMapping; +import com.iemr.common.service.directory.DirectoryMappingService; +import com.iemr.common.service.directory.DirectoryService; +import com.iemr.common.service.directory.SubDirectoryService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class DirectoryControllerTest { + + @InjectMocks + DirectoryController directoryController; + + @Mock + private DirectoryService directoryService; + + @Mock + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private InputMapper inputMapper = new InputMapper(); + + @Mock + private SubDirectoryService subDirectoryService; + @Mock + private DirectoryMappingService directoryMappingService; + + @Test + void testGetDirectoryWithException() { + // Arrange + String errorMessage = "Failed to get directories"; + when(directoryService.getDirectories()).thenThrow(new RuntimeException(errorMessage)); + + // Act + String result = directoryController.getDirectory(); + + // Assert + assertNotNull(result); + assertTrue(result.contains("error")); + verify(directoryService).getDirectories(); // Verify getDirectories() was called + } + +// +// @Test +// void testGetDirectoryV1() { +// fail("Not yet implemented"); +// } + + @Test + void testGetDirectoryV1WithException() { + // Arrange + String directoryRequest = ""; + + String errorMessage = "Failed to get directories"; + + // Act + String result = directoryController.getDirectoryV1(directoryRequest); + + // Assert + assertNotNull(result); + assertTrue(result.contains("error")); + } + +// @Test +// void testGetSubDirectory() { +// fail("Not yet implemented"); +// } + + @Test + void testGetSubDirectoryWithException() { + // Arrange + String subDirectoryRequest = ""; + + String errorMessage = "Failed to get directories"; + + // Act + String result = directoryController.getSubDirectory(subDirectoryRequest); + + // Assert + assertNotNull(result); + assertTrue(result.contains("error")); + } + + @Test + void testGetInstitutesDirectories_Exception() throws IEMRException, JsonMappingException, JsonProcessingException { + // Prepare input JSON + String requestJson = "{\"instituteDirectoryID\":\"1\", ...}"; + + // Mock the service to throw an exception + when(directoryMappingService.findAciveInstituteDirectories(anyString())) + .thenThrow(new RuntimeException("Database error")); + + // Execute the method + String result = directoryController.getInstitutesDirectories(requestJson); + + // Verify + assertNotNull(result); + assertTrue(result.contains("error")); // Assuming your OutputResponse's toString includes "error" on exceptions + } + +} diff --git a/src/test/java/com/iemr/common/controller/door_to_door_app/DoorToDoorAppControllerTest.java b/src/test/java/com/iemr/common/controller/door_to_door_app/DoorToDoorAppControllerTest.java new file mode 100644 index 00000000..302ced42 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/door_to_door_app/DoorToDoorAppControllerTest.java @@ -0,0 +1,102 @@ +package com.iemr.common.controller.door_to_door_app; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.data.door_to_door_app.RequestParser; +import com.iemr.common.service.door_to_door_app.DoorToDoorService; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class DoorToDoorAppControllerTest { + + @InjectMocks + DoorToDoorAppController doorToDoorAppController; + + @Mock + private DoorToDoorService doorToDoorService; + private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void testGetUserDetails() throws Exception { + OutputResponse response = new OutputResponse(); + RequestParser rp = new RequestParser(); + rp.setUserID(123); + rp.setBenRegID(12L); + rp.setSuspectedHRP("hrp"); + rp.setSuspectedNCD("ncd"); + rp.setSuspectedTB("tb"); + rp.setVisitCode(523L); + rp.toString(); + String requestObj = rp.toString(); + when(doorToDoorService.getUserDetails(requestObj)).thenReturn(requestObj); + response.setResponse(requestObj.toString()); + String expResp = "Exp Resp"; + String actualResp = doorToDoorAppController.getUserDetails(requestObj); + assertNotNull(actualResp); + Assertions.assertEquals(response.toString(), doorToDoorAppController.getUserDetails(requestObj)); + } + + @Test + void testGetUserDetails_InvalidRequest() throws Exception { + String invalidRequestObj = "{\"someInvalidField\": \"value\"}"; // An example of an invalid request object + String response = doorToDoorAppController.getUserDetails(invalidRequestObj); + assertTrue(response.contains("user details not found"), "Expected error message not found in the response."); + } + + @Test + void testGetUserDetails_CatchBlock() throws Exception { + String requestObj = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(doorToDoorService.getUserDetails(requestObj)).thenThrow(NotFoundException.class); + String response = doorToDoorAppController.getUserDetails(requestObj); + Assertions.assertEquals(response, doorToDoorAppController.getUserDetails(requestObj)); + } + + @Test + void testGetSuspectedData_HRP_TB_NCD() throws Exception { + OutputResponse response = new OutputResponse(); + RequestParser rp = new RequestParser(); + rp.setUserID(123); + rp.setBenRegID(12L); + rp.setSuspectedHRP("hrp"); + rp.setSuspectedNCD("ncd"); + rp.setSuspectedTB("tb"); + rp.setVisitCode(523L); + rp.toString(); + String s = rp.toString(); + String requestObj = s; + response.setResponse(requestObj.toString()); + String actualResp = doorToDoorAppController.getSuspectedData_HRP_TB_NCD(requestObj); + assertNotNull(actualResp); + Assertions.assertEquals(actualResp, doorToDoorAppController.getSuspectedData_HRP_TB_NCD(requestObj)); + } + + @Test + void testGetSuspectedData_HRP_TB_NCD_InvalidRequest() throws Exception { + String invalidRequestObj = "{\"someInvalidField\": \"value\"}"; + String response = doorToDoorAppController.getSuspectedData_HRP_TB_NCD(invalidRequestObj); + assertTrue(response.contains("Error in getting suspected information"), "Expected error message not found in the response."); + } + + @Test + void testGetSuspectedData_HRP_TB_NCD_CatchBlock() throws Exception { + String requestObj = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + RequestParser rp = new RequestParser(); + rp.setUserID(123); + when(doorToDoorService.get_NCD_TB_HRP_Suspected_Status(rp)).thenThrow(NotFoundException.class); + String response = doorToDoorAppController.getSuspectedData_HRP_TB_NCD(requestObj); + Assertions.assertEquals(response, doorToDoorAppController.getSuspectedData_HRP_TB_NCD(requestObj)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/eausadha/EAusadhaControllerTest.java b/src/test/java/com/iemr/common/controller/eausadha/EAusadhaControllerTest.java new file mode 100644 index 00000000..1ee7dc55 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/eausadha/EAusadhaControllerTest.java @@ -0,0 +1,57 @@ +package com.iemr.common.controller.eausadha; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.time.Instant; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.model.eAusadha.EAusadhaDTO; +import com.iemr.common.service.beneficiary.EAusadhaService; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class EAusadhaControllerTest { + + @InjectMocks + EAusadhaController eAusadhaController; + + @Mock + private EAusadhaService eAusadhaService; + private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void testCreateEAusadha() throws Exception { + OutputResponse response = new OutputResponse(); + String Authorization = "authorization"; + EAusadhaDTO eAusadhaDTO = new EAusadhaDTO(); + eAusadhaDTO.setFacilityId(123); + eAusadhaDTO.setInwardDate(Timestamp.from(Instant.now())); + String res = eAusadhaDTO.toString(); + when(eAusadhaService.createEAusadha(eAusadhaDTO, Authorization)).thenReturn(res); + response.setResponse(res.toString()); + Assertions.assertEquals(response.toString(), eAusadhaController.createEAusadha(eAusadhaDTO, Authorization)); + } + + @Test + void testCreateEAusadha_CatchBlock() throws Exception { + String Authorization = "authorization"; + EAusadhaDTO eAusadhaDTO = new EAusadhaDTO(); + eAusadhaDTO.setFacilityId(123); + when(eAusadhaService.createEAusadha(eAusadhaDTO, Authorization)).thenThrow(NotFoundException.class); + String response = eAusadhaController.createEAusadha(eAusadhaDTO, Authorization); + Assertions.assertEquals(response, eAusadhaController.createEAusadha(eAusadhaDTO, Authorization)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/email/EmailControllerTest.java b/src/test/java/com/iemr/common/controller/email/EmailControllerTest.java new file mode 100644 index 00000000..d340af04 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/email/EmailControllerTest.java @@ -0,0 +1,134 @@ +package com.iemr.common.controller.email; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.time.Instant; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.data.email.EmailNotification; +import com.iemr.common.data.feedback.FeedbackDetails; +import com.iemr.common.model.email.EmailRequest; +import com.iemr.common.model.feedback.AuthorityEmailID; +import com.iemr.common.service.email.EmailService; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class EmailControllerTest { + + @InjectMocks + EmailController emailController; + + InputMapper inputMapper = new InputMapper(); + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + @Mock + private EmailService emailService; + + + @Test + void testSendEmail() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String auth = serverRequest.getHeader("Authorization"); + EmailNotification notification = new EmailNotification(); + notification.setFeedbackID(123L); + notification.setEmailID("email id"); + notification.setIs1097(true); + notification.setBenCallID(23L); + notification.setBeneficiaryRegID(1234L); + notification.setCreatedBy("createdBy"); + notification.setCreatedDate(Timestamp.from(Instant.now())); + notification.setDeleted(false); + notification.setEmail("email"); + notification.setEmailNotificationID(234); + notification.setEmailSentDate(Timestamp.from(Instant.now())); + notification.setEmailStatus(123); + notification.setEmailTemplateID(5432); + notification.setIsTransactionError(false); + notification.setPhoneNo("ph no"); + notification.setProviderServiceMapID(3478); + notification.setReceivingUserID(7654); + notification.setSenderID(765); + notification.setTransactionError("trans error"); + notification.setTransactionID("trans id"); + notification.toString(); + String request = notification.toString(); + when(emailService.SendEmail(request, auth)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), emailController.SendEmail(request, serverRequest)); + } + + @Test + void testSendEmail_CatchBlock() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String auth = serverRequest.getHeader("Authorization"); + when(emailService.SendEmail(request, auth)).thenThrow(NotFoundException.class); + String response = emailController.SendEmail(request, serverRequest); + Assertions.assertEquals(response, emailController.SendEmail(request, serverRequest)); + } + + @Test + void testGetAuthorityEmailID() throws Exception { + OutputResponse response = new OutputResponse(); + AuthorityEmailID authorityEmailID = new AuthorityEmailID(); + authorityEmailID.setDistrictID(123); + authorityEmailID.setAuthorityEmailID(12345); + authorityEmailID.setDeleted(false); + authorityEmailID.setEmailID("email id"); + authorityEmailID.toString(); + String severityRequest = authorityEmailID.toString(); + when(emailService.getAuthorityEmailID(severityRequest)).thenReturn(severityRequest); + response.setResponse(severityRequest.toString()); + Assertions.assertEquals(response.toString(), emailController.getAuthorityEmailID(severityRequest)); + } + + @Test + void testGetAuthorityEmailID_CatchBlock() throws Exception { + String severityRequest = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(emailService.getAuthorityEmailID(severityRequest)).thenThrow(NotFoundException.class); + String response = emailController.getAuthorityEmailID(severityRequest); + Assertions.assertEquals(response, emailController.getAuthorityEmailID(severityRequest)); + } + + @Test + void testSendEmailGeneral() throws Exception { + OutputResponse response = new OutputResponse(); + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String auth = serverRequest.getHeader("Authorization"); + EmailRequest emailReq = new EmailRequest(); + emailReq.setRequestID("req id"); + emailReq.setEmailType("email type"); + emailReq.setEmailID("email id"); + emailReq.toString(); + String requestID = emailReq.toString(); + when(emailService.sendEmailGeneral(requestID, auth)).thenReturn(requestID); + response.setResponse(requestID.toString()); + Assertions.assertEquals(response.toString(), emailController.sendEmailGeneral(requestID, serverRequest)); + } + + @Test + void testSendEmailGeneral_CatchBlock() throws Exception { + String requestID = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + String auth = serverRequest.getHeader("Authorization"); + when(emailService.sendEmailGeneral(requestID, auth)).thenThrow(NotFoundException.class); + String response = emailController.sendEmailGeneral(requestID, serverRequest); + Assertions.assertEquals(response, emailController.sendEmailGeneral(requestID, serverRequest)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/esanjeevani/ESanjeevaniControllerTest.java b/src/test/java/com/iemr/common/controller/esanjeevani/ESanjeevaniControllerTest.java new file mode 100644 index 00000000..fe3a877e --- /dev/null +++ b/src/test/java/com/iemr/common/controller/esanjeevani/ESanjeevaniControllerTest.java @@ -0,0 +1,72 @@ +package com.iemr.common.controller.esanjeevani; + +import static org.assertj.core.api.Assertions.setAllowComparingPrivateFields; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.model.esanjeevani.ESanjeevaniPatientRegistration; +import com.iemr.common.service.esanjeevani.ESanjeevaniService; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class ESanjeevaniControllerTest { + + @InjectMocks + ESanjeevaniController eSanjeevaniController; + @Mock + private ESanjeevaniService eSanjeevaniService; + + private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void testRegisterESanjeevaniPatient() throws Exception { + OutputResponse response = new OutputResponse(); + Long beneficiaryReqId = 123L; + ESanjeevaniPatientRegistration reqObj = new ESanjeevaniPatientRegistration(); + reqObj.setAbhaAddress("abha address"); + reqObj.setAbhaNumber("abha num"); + reqObj.setAge(23); + reqObj.setBirthdate("birth date"); + reqObj.setBlock(false); + reqObj.setDisplayName("display name"); + reqObj.setFirstName("first name"); + reqObj.setGenderCode(443); + reqObj.setLastName("last name"); + reqObj.setMiddleName("middle name"); + reqObj.setSource("source"); + reqObj.toString(); + String res = reqObj.toString(); + when(eSanjeevaniService.registerPatient(beneficiaryReqId)).thenReturn(res); + response.setResponse(res.toString()); + String actualResp = eSanjeevaniController.registerESanjeevaniPatient(beneficiaryReqId); + assertNotNull(actualResp); + Assertions.assertEquals(response.toString(), actualResp); + } + + @Test + void testRegisterESanjeevaniPatient_InvalidReq() throws Exception { + Long beneficiaryReqId = null; + String response = eSanjeevaniController.registerESanjeevaniPatient(beneficiaryReqId); + assertTrue(response.contains("Error while fetching E-sanjeevani route URL"), "Expected error message not found in the response."); + } + + @Test + void testRegisterESanjeevaniPatient_CatchBlock() throws Exception { + Long beneficiaryReqId = null; + when(eSanjeevaniService.registerPatient(beneficiaryReqId)).thenThrow(NotFoundException.class); + String response = eSanjeevaniController.registerESanjeevaniPatient(beneficiaryReqId); + Assertions.assertEquals(response, eSanjeevaniController.registerESanjeevaniPatient(beneficiaryReqId)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/everwell/callhandle/EverwellCallControllerTest.java b/src/test/java/com/iemr/common/controller/everwell/callhandle/EverwellCallControllerTest.java new file mode 100644 index 00000000..6f076a5c --- /dev/null +++ b/src/test/java/com/iemr/common/controller/everwell/callhandle/EverwellCallControllerTest.java @@ -0,0 +1,529 @@ +package com.iemr.common.controller.everwell.callhandle; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.text.ParseException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.data.everwell.EverwellAllocateMultiple; +import com.iemr.common.data.everwell.EverwellDetails; +import com.iemr.common.data.everwell.EverwellFeedback; +import com.iemr.common.service.callhandling.CalltypeServiceImpl; +import com.iemr.common.service.everwell.EverwellCallHandlingService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class EverwellCallControllerTest { + + @InjectMocks + EverwellCallController everwellCallController; + + @Mock + private EverwellCallHandlingService beneficiaryCallService; + + InputMapper inputMapper = new InputMapper(); + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void testOutboundCallCount() throws IEMRException, JSONException { + OutputResponse response = new OutputResponse(); + EverwellDetails outboundCallRequest = new EverwellDetails(); + outboundCallRequest.setProviderServiceMapId(1261); + outboundCallRequest.setAssignedUserID(12); + outboundCallRequest.setActionTaken("action taken"); + outboundCallRequest.setAdherencePercentage(54); + outboundCallRequest.setAdherenceString("adher"); + outboundCallRequest.setAgentId(54); + outboundCallRequest.setBenCallID(123L); + outboundCallRequest.setBeneficiaryID(65432L); + outboundCallRequest.setBeneficiaryRegId(654321L); + outboundCallRequest.setCallCounter(6); + outboundCallRequest.setCallId("call id"); + outboundCallRequest.setCallTypeID(4); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setCurrentMonthMissedDoses(3); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setDistrict("district"); + outboundCallRequest.setEapiId(54L); + outboundCallRequest.setFacilityName("facility name"); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFirstName("first name"); + outboundCallRequest.setGender("female"); + outboundCallRequest.setId(12L); + outboundCallRequest.setIsAllocated(false); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsRegistered(false); + outboundCallRequest.setLastCall("last call"); + outboundCallRequest.setLastName("last name"); + outboundCallRequest.setParkingPlaceId(12); + outboundCallRequest.setModifiedBy("modified by"); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.outboundCallCount(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), everwellCallController.outboundCallCount(request)); + } + + @Test + void testOutboundCallCount_CatchBlock() throws IEMRException, JSONException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.outboundCallCount(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.outboundCallCount(request); + Assertions.assertEquals(response, everwellCallController.outboundCallCount(request)); + } + + @Test + void testOutboundAllocation() throws IEMRException { + OutputResponse response = new OutputResponse(); + EverwellAllocateMultiple allocation = new EverwellAllocateMultiple(); + List<Integer> agentIds = new ArrayList<Integer>(); + agentIds.add(1); + agentIds.add(2); + allocation.setAgentId(agentIds); + allocation.setAllocateNo(12); + EverwellDetails[] outboundCallRequests = { new EverwellDetails() }; + allocation.setOutboundCallRequests(outboundCallRequests); + allocation.toString(); + String request = allocation.toString(); + when(beneficiaryCallService.outboundAllocation(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), everwellCallController.outboundAllocation(request)); + } + + @Test + void testOutboundAllocation_CatchBlock() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.outboundAllocation(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.outboundAllocation(request); + Assertions.assertEquals(response, everwellCallController.outboundAllocation(request)); + } + + @Test + void testOutboundCallList() throws IEMRException { + OutputResponse response = new OutputResponse(); + EverwellDetails outboundCallRequest = new EverwellDetails(); + outboundCallRequest.setProviderServiceMapId(1261); + outboundCallRequest.setAssignedUserID(12); + outboundCallRequest.setActionTaken("action taken"); + outboundCallRequest.setAdherencePercentage(54); + outboundCallRequest.setAdherenceString("adher"); + outboundCallRequest.setAgentId(54); + outboundCallRequest.setBenCallID(123L); + outboundCallRequest.setBeneficiaryID(65432L); + outboundCallRequest.setBeneficiaryRegId(654321L); + outboundCallRequest.setCallCounter(6); + outboundCallRequest.setCallId("call id"); + outboundCallRequest.setCallTypeID(4); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setCurrentMonthMissedDoses(3); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setDistrict("district"); + outboundCallRequest.setEapiId(54L); + outboundCallRequest.setFacilityName("facility name"); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFirstName("first name"); + outboundCallRequest.setGender("female"); + outboundCallRequest.setId(12L); + outboundCallRequest.setIsAllocated(false); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsRegistered(false); + outboundCallRequest.setLastCall("last call"); + outboundCallRequest.setLastName("last name"); + outboundCallRequest.setParkingPlaceId(12); + outboundCallRequest.setModifiedBy("modified by"); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.outboundCallList(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), everwellCallController.outboundCallList(request)); + } + + @Test + void testOutboundCallList_CatchBlock() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.outboundCallList(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.outboundCallList(request); + Assertions.assertEquals(response, everwellCallController.outboundCallList(request)); + } + + @Test + void testResetOutboundCall() throws IEMRException { + OutputResponse response = new OutputResponse(); + EverwellDetails outboundCallRequest = new EverwellDetails(); + List<Long> eapiIds = new ArrayList<Long>(); + eapiIds.add(12L); + eapiIds.add(32L); + outboundCallRequest.setEapiIds(eapiIds); + outboundCallRequest.setProviderServiceMapId(1261); + outboundCallRequest.setAssignedUserID(12); + outboundCallRequest.setActionTaken("action taken"); + outboundCallRequest.setAdherencePercentage(54); + outboundCallRequest.setAdherenceString("adher"); + outboundCallRequest.setAgentId(54); + outboundCallRequest.setBenCallID(123L); + outboundCallRequest.setBeneficiaryID(65432L); + outboundCallRequest.setBeneficiaryRegId(654321L); + outboundCallRequest.setCallCounter(6); + outboundCallRequest.setCallId("call id"); + outboundCallRequest.setCallTypeID(4); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setCurrentMonthMissedDoses(3); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setDistrict("district"); + outboundCallRequest.setEapiId(54L); + outboundCallRequest.setFacilityName("facility name"); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFirstName("first name"); + outboundCallRequest.setGender("female"); + outboundCallRequest.setId(12L); + outboundCallRequest.setIsAllocated(false); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsRegistered(false); + outboundCallRequest.setLastCall("last call"); + outboundCallRequest.setLastName("last name"); + outboundCallRequest.setParkingPlaceId(12); + outboundCallRequest.setModifiedBy("modified by"); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.resetOutboundCall(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), everwellCallController.resetOutboundCall(request)); + } + + @Test + void testResetOutboundCall_CatchBlock() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.resetOutboundCall(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.resetOutboundCall(request); + Assertions.assertEquals(response, everwellCallController.resetOutboundCall(request)); + } + + @Test + void testSaveCallDetails() throws IEMRException, ParseException { + OutputResponse response = new OutputResponse(); + EverwellDetails outboundCallRequest = new EverwellDetails(); + List<Long> eapiIds = new ArrayList<Long>(); + eapiIds.add(12L); + eapiIds.add(32L); + outboundCallRequest.setEapiIds(eapiIds); + outboundCallRequest.setProviderServiceMapId(1261); + outboundCallRequest.setAssignedUserID(12); + outboundCallRequest.setActionTaken("action taken"); + outboundCallRequest.setAdherencePercentage(54); + outboundCallRequest.setAdherenceString("adher"); + outboundCallRequest.setAgentId(54); + outboundCallRequest.setBenCallID(123L); + outboundCallRequest.setBeneficiaryID(65432L); + outboundCallRequest.setBeneficiaryRegId(654321L); + outboundCallRequest.setCallCounter(6); + outboundCallRequest.setCallId("call id"); + outboundCallRequest.setCallTypeID(4); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setCurrentMonthMissedDoses(3); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setDistrict("district"); + outboundCallRequest.setEapiId(54L); + outboundCallRequest.setFacilityName("facility name"); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFirstName("first name"); + outboundCallRequest.setGender("female"); + outboundCallRequest.setId(12L); + outboundCallRequest.setIsAllocated(false); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsRegistered(false); + outboundCallRequest.setLastCall("last call"); + outboundCallRequest.setLastName("last name"); + outboundCallRequest.setParkingPlaceId(12); + outboundCallRequest.setModifiedBy("modified by"); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.saveDetails(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), everwellCallController.saveCallDetails(request)); + } + + @Test + void testSaveCallDetails_CatchBlock() throws IEMRException, ParseException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.saveDetails(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.saveCallDetails(request); + Assertions.assertEquals(response, everwellCallController.saveCallDetails(request)); + } + + @Test + void testCompleteOutboundCall() throws IEMRException { + OutputResponse response = new OutputResponse(); + EverwellDetails outboundCallRequest = new EverwellDetails(); + List<Long> eapiIds = new ArrayList<Long>(); + eapiIds.add(12L); + eapiIds.add(32L); + outboundCallRequest.setEapiIds(eapiIds); + outboundCallRequest.setProviderServiceMapId(1261); + outboundCallRequest.setAssignedUserID(12); + outboundCallRequest.setActionTaken("action taken"); + outboundCallRequest.setAdherencePercentage(54); + outboundCallRequest.setAdherenceString("adher"); + outboundCallRequest.setAgentId(54); + outboundCallRequest.setBenCallID(123L); + outboundCallRequest.setBeneficiaryID(65432L); + outboundCallRequest.setBeneficiaryRegId(654321L); + outboundCallRequest.setCallCounter(6); + outboundCallRequest.setCallId("call id"); + outboundCallRequest.setCallTypeID(4); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setCurrentMonthMissedDoses(3); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setDistrict("district"); + outboundCallRequest.setEapiId(54L); + outboundCallRequest.setFacilityName("facility name"); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFirstName("first name"); + outboundCallRequest.setGender("female"); + outboundCallRequest.setId(12L); + outboundCallRequest.setIsAllocated(false); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsRegistered(false); + outboundCallRequest.setLastCall("last call"); + outboundCallRequest.setLastName("last name"); + outboundCallRequest.setParkingPlaceId(12); + outboundCallRequest.setModifiedBy("modified by"); + outboundCallRequest.setMissedDoses(2); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.completeOutboundCall(request)).thenReturn("success"); + response.setResponse("success"); + String actualResp = everwellCallController.completeOutboundCall(request); + assertTrue(actualResp.toLowerCase().contains("success"), + "Expected 'success' in the response, but got: " + actualResp); + Assertions.assertEquals(response.toString(), actualResp); + } + + @Test + void testCompleteOutboundCall_InvalidRequest() throws IEMRException { + OutputResponse response = new OutputResponse(); + String invalidRequestObj = "{\"someInvalidField\": \"value\"}"; + String expResp = everwellCallController.completeOutboundCall(invalidRequestObj); + response.setError(5000, "error in updating data"); + Assertions.assertEquals(expResp, everwellCallController.completeOutboundCall(invalidRequestObj)); + assertTrue(response.toString().contains("error in updating data")); + } + + @Test + void testCompleteOutboundCall_CatchBlock() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.completeOutboundCall(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.completeOutboundCall(request); + Assertions.assertEquals(response, everwellCallController.completeOutboundCall(request)); + } + + @Test + void testGetEverwellfeedbackDetails() throws IEMRException { + OutputResponse response = new OutputResponse(); + EverwellFeedback outboundCallRequest = new EverwellFeedback(); + outboundCallRequest.setActionTaken("sc"); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setEapiId(123L); + outboundCallRequest.setEfid(43L); + outboundCallRequest.setId(4432L); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsManualDoseProcessed(false); + outboundCallRequest.setIsMobileNumberProcessed(true); + outboundCallRequest.setIsMissedDoseProcessed(false); + outboundCallRequest.setIsSupportActionProcessed(true); + outboundCallRequest.setModifiedBy("modifiedby"); + outboundCallRequest.setProviderServiceMapId(123); + outboundCallRequest.setSecondaryPhoneNo("sec ph"); + outboundCallRequest.setSubCategory("sub cat"); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.getEverwellFeedback(request)).thenReturn(request); + response.setResponse(request.toString()); + String actualResp = everwellCallController.getEverwellfeedbackDetails(request); + assertNotNull(actualResp); + Assertions.assertEquals(response.toString(), actualResp); + } + + @Test + void testGetEverwellfeedbackDetails_InvalidRequest() throws IEMRException { + OutputResponse response = new OutputResponse(); + String invalidRequestObj = "{\"someInvalidField\": \"value\"}"; + String expResp = everwellCallController.getEverwellfeedbackDetails(invalidRequestObj); + response.setError(5000, "error in fetching data"); + Assertions.assertEquals(expResp, everwellCallController.getEverwellfeedbackDetails(invalidRequestObj)); + assertTrue(response.toString().contains("error in fetching data")); + } + + @Test + void testGetEverwellfeedbackDetails_CatchBlock() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.getEverwellFeedback(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.getEverwellfeedbackDetails(request); + Assertions.assertEquals(response, everwellCallController.getEverwellfeedbackDetails(request)); + } + + @Test + void testOutboundCallListWithMobileNumber() throws IEMRException { + OutputResponse response = new OutputResponse(); + EverwellDetails outboundCallRequest = new EverwellDetails(); + List<Long> eapiIds = new ArrayList<Long>(); + eapiIds.add(12L); + eapiIds.add(32L); + outboundCallRequest.setEapiIds(eapiIds); + outboundCallRequest.setProviderServiceMapId(1261); + outboundCallRequest.setAssignedUserID(12); + outboundCallRequest.setActionTaken("action taken"); + outboundCallRequest.setAdherencePercentage(54); + outboundCallRequest.setAdherenceString("adher"); + outboundCallRequest.setAgentId(54); + outboundCallRequest.setBenCallID(123L); + outboundCallRequest.setBeneficiaryID(65432L); + outboundCallRequest.setBeneficiaryRegId(654321L); + outboundCallRequest.setCallCounter(6); + outboundCallRequest.setCallId("call id"); + outboundCallRequest.setCallTypeID(4); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setCurrentMonthMissedDoses(3); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setDistrict("district"); + outboundCallRequest.setEapiId(54L); + outboundCallRequest.setFacilityName("facility name"); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFirstName("first name"); + outboundCallRequest.setGender("female"); + outboundCallRequest.setId(12L); + outboundCallRequest.setIsAllocated(false); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsRegistered(false); + outboundCallRequest.setLastCall("last call"); + outboundCallRequest.setLastName("last name"); + outboundCallRequest.setParkingPlaceId(12); + outboundCallRequest.setModifiedBy("modified by"); + outboundCallRequest.setMissedDoses(2); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.outboundCallListWithMobileNumber(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), everwellCallController.outboundCallListWithMobileNumber(request)); + } + + @Test + void testOutboundCallListWithMobileNumber_CatchBlock() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.outboundCallListWithMobileNumber(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.outboundCallListWithMobileNumber(request); + Assertions.assertEquals(response, everwellCallController.outboundCallListWithMobileNumber(request)); + } + + @Test + void testCheckIfCalledOrNot() throws IEMRException { + OutputResponse response = new OutputResponse(); + EverwellDetails outboundCallRequest = new EverwellDetails(); + List<Long> eapiIds = new ArrayList<Long>(); + eapiIds.add(12L); + eapiIds.add(32L); + outboundCallRequest.setEapiIds(eapiIds); + outboundCallRequest.setProviderServiceMapId(1261); + outboundCallRequest.setAssignedUserID(12); + outboundCallRequest.setActionTaken("action taken"); + outboundCallRequest.setAdherencePercentage(54); + outboundCallRequest.setAdherenceString("adher"); + outboundCallRequest.setAgentId(54); + outboundCallRequest.setBenCallID(123L); + outboundCallRequest.setBeneficiaryID(65432L); + outboundCallRequest.setBeneficiaryRegId(654321L); + outboundCallRequest.setCallCounter(6); + outboundCallRequest.setCallId("call id"); + outboundCallRequest.setCallTypeID(4); + outboundCallRequest.setCategory("category"); + outboundCallRequest.setComments("comments"); + outboundCallRequest.setCreatedBy("createdby"); + outboundCallRequest.setCreatedDate(Timestamp.from(Instant.now())); + outboundCallRequest.setCurrentMonthMissedDoses(3); + outboundCallRequest.setDateOfAction(Timestamp.from(Instant.now())); + outboundCallRequest.setDeleted(false); + outboundCallRequest.setDistrict("district"); + outboundCallRequest.setEapiId(54L); + outboundCallRequest.setFacilityName("facility name"); + outboundCallRequest.setFilterEndDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFilterStartDate(Timestamp.from(Instant.now())); + outboundCallRequest.setFirstName("first name"); + outboundCallRequest.setGender("female"); + outboundCallRequest.setId(12L); + outboundCallRequest.setIsAllocated(false); + outboundCallRequest.setIsCompleted(true); + outboundCallRequest.setIsRegistered(false); + outboundCallRequest.setLastCall("last call"); + outboundCallRequest.setLastName("last name"); + outboundCallRequest.setParkingPlaceId(12); + outboundCallRequest.setModifiedBy("modified by"); + outboundCallRequest.setMissedDoses(2); + outboundCallRequest.toString(); + String request = outboundCallRequest.toString(); + when(beneficiaryCallService.checkAlreadyCalled(request)).thenReturn(request); + response.setResponse(request.toString()); + Assertions.assertEquals(response.toString(), everwellCallController.checkIfCalledOrNot(request)); + } + + @Test + void testCheckIfCalledOrNot_CatchBlock() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(beneficiaryCallService.checkAlreadyCalled(request)).thenThrow(NotFoundException.class); + String response = everwellCallController.checkIfCalledOrNot(request); + Assertions.assertEquals(response, everwellCallController.checkIfCalledOrNot(request)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/everwellTest/EverwellControllerTest.java b/src/test/java/com/iemr/common/controller/everwellTest/EverwellControllerTest.java new file mode 100644 index 00000000..ead9ac32 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/everwellTest/EverwellControllerTest.java @@ -0,0 +1,134 @@ +package com.iemr.common.controller.everwellTest; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.apache.catalina.User; +import org.apache.catalina.realm.UserDatabaseRealm; +import org.apache.catalina.users.MemoryUserDatabase; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.common.model.user.LoginRequestModelEverwell; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class EverwellControllerTest { + @Mock + private EverwellController everwellController; + + @Test + void testAddSupportAction() throws Exception { + // Arrange + MockHttpServletRequestBuilder contentTypeResult = MockMvcRequestBuilders + .post("/everwell/addSupportAction/{id}", 1L).contentType(MediaType.APPLICATION_JSON); + MockHttpServletRequestBuilder requestBuilder = contentTypeResult + .content((new ObjectMapper()).writeValueAsString("foo")); + + // Act + ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(everwellController).build() + .perform(requestBuilder); + + // Assert + actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); + } + + @Test + void testAddSupportAction2() throws Exception { + // Arrange + User user = mock(User.class); + when(user.getName()).thenReturn("Name"); + MockHttpServletRequestBuilder postResult = MockMvcRequestBuilders.post("/everwell/addSupportAction/{id}", 1L); + postResult.principal(new UserDatabaseRealm.UserDatabasePrincipal(user, new MemoryUserDatabase())); + MockHttpServletRequestBuilder contentTypeResult = postResult.contentType(MediaType.APPLICATION_JSON); + MockHttpServletRequestBuilder requestBuilder = contentTypeResult + .content((new ObjectMapper()).writeValueAsString("foo")); + + // Act + ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(everwellController).build() + .perform(requestBuilder); + + // Assert + actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); + } + + @Test + void testEditManualDoses() throws Exception { + // Arrange + MockHttpServletRequestBuilder contentTypeResult = MockMvcRequestBuilders + .post("/everwell/editManualDoses/{id}", 1L).contentType(MediaType.APPLICATION_JSON); + MockHttpServletRequestBuilder requestBuilder = contentTypeResult + .content((new ObjectMapper()).writeValueAsString("foo")); + + // Act + ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(everwellController).build() + .perform(requestBuilder); + + // Assert + actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); + } + + @Test + void testEditManualDoses2() throws Exception { + // Arrange + User user = mock(User.class); + when(user.getName()).thenReturn("Name"); + MockHttpServletRequestBuilder postResult = MockMvcRequestBuilders.post("/everwell/editManualDoses/{id}", 1L); + postResult.principal(new UserDatabaseRealm.UserDatabasePrincipal(user, new MemoryUserDatabase())); + MockHttpServletRequestBuilder contentTypeResult = postResult.contentType(MediaType.APPLICATION_JSON); + MockHttpServletRequestBuilder requestBuilder = contentTypeResult + .content((new ObjectMapper()).writeValueAsString("foo")); + + // Act + ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(everwellController).build() + .perform(requestBuilder); + + // Assert + actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); + } + + @Test + void testEverwellLogin() throws Exception { + // Arrange + LoginRequestModelEverwell loginRequestModelEverwell = new LoginRequestModelEverwell(); + loginRequestModelEverwell.setEverwellAuthKey("Everwell Auth Key"); + loginRequestModelEverwell.setEverwellPassword("iloveyou"); + loginRequestModelEverwell.setEverwellUserName("janedoe"); + String content = (new ObjectMapper()).writeValueAsString(loginRequestModelEverwell); + MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/everwell/login") + .contentType(MediaType.APPLICATION_JSON).content(content); + + // Act + ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(everwellController).build() + .perform(requestBuilder); + + // Assert + actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); + } + + @Test + void testGetdata() throws Exception { + // Arrange + MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/everwell/getjson"); + + // Act + ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(everwellController).build() + .perform(requestBuilder); + + // Assert + actualPerformResult.andExpect(MockMvcResultMatchers.status().isNotFound()); + } + +} diff --git a/src/test/java/com/iemr/common/controller/feedback/FeedbackControllerTest.java b/src/test/java/com/iemr/common/controller/feedback/FeedbackControllerTest.java new file mode 100644 index 00000000..2423cce6 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/feedback/FeedbackControllerTest.java @@ -0,0 +1,1173 @@ +package com.iemr.common.controller.feedback; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.iemr.common.data.feedback.FeedbackDetails; +import com.iemr.common.data.feedback.FeedbackLog; +import com.iemr.common.data.feedback.FeedbackResponse; +import com.iemr.common.data.feedback.FeedbackSeverity; +import com.iemr.common.data.feedback.FeedbackType; +import com.iemr.common.model.feedback.FeedbackListRequestModel; +import com.iemr.common.service.feedback.FeedbackRequestService; +import com.iemr.common.service.feedback.FeedbackResponseService; +import com.iemr.common.service.feedback.FeedbackService; +import com.iemr.common.service.feedback.FeedbackSeverityServiceImpl; +import com.iemr.common.service.feedback.FeedbackTypeService; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.mapper.OutputMapper; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.NotFoundException; + +@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) +@ExtendWith(MockitoExtension.class) +class FeedbackControllerTest { + + private final FeedbackService feedbackServiceMock = mock(FeedbackService.class, "feedbackService"); + + private final FeedbackRequestService feedbackRequestServiceMock = mock(FeedbackRequestService.class, + "feedbackRequestService"); + + private final FeedbackResponseService feedbackResponseServiceMock = mock(FeedbackResponseService.class, + "feedbackResponseService"); + + private final FeedbackSeverityServiceImpl feedbackSeverityServiceMock = mock(FeedbackSeverityServiceImpl.class, + "feedbackSeverityService"); + + private final FeedbackTypeService feedbackTypeServiceMock = mock(FeedbackTypeService.class, "feedbackTypeService"); + + private AutoCloseable autoCloseableMocks; + + @InjectMocks() + private FeedbackController target; + + @AfterEach() + void afterTest() throws Exception { + if (autoCloseableMocks != null) + autoCloseableMocks.close(); + } + + @Test() + void feedbackRequestTest() throws Exception { + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + FeedbackDetails feedbackDetailsMock = mock(FeedbackDetails.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + doReturn(feedbackDetailsMock).when(inputMapperMock).fromJson("request1", FeedbackDetails.class); + doReturn(0L).when(feedbackDetailsMock).getBeneficiaryRegID(); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + List<FeedbackDetails> feedbackDetailsList = new ArrayList<>(); + doReturn(feedbackDetailsList).when(feedbackServiceMock).getFeedbackRequests(0L); + // Act Statement(s) + String result = target.feedbackRequest("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":[],\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("request1", FeedbackDetails.class); + verify(feedbackDetailsMock).getBeneficiaryRegID(); + verify(feedbackServiceMock).getFeedbackRequests(0L); + }); + } + } + + @Test() + void feedbackRequestWhenCaughtException() throws Exception { + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + FeedbackDetails feedbackDetailsMock = mock(FeedbackDetails.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + doReturn(feedbackDetailsMock).when(inputMapperMock).fromJson("request1", FeedbackDetails.class); + doReturn(0L).when(feedbackDetailsMock).getBeneficiaryRegID(); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + List<FeedbackDetails> feedbackDetailsList = new ArrayList<>(); + doReturn(feedbackDetailsList).when(feedbackServiceMock).getFeedbackRequests(0L); + // Act Statement(s) + String result = target.feedbackRequest("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":[],\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("request1", FeedbackDetails.class); + verify(feedbackDetailsMock).getBeneficiaryRegID(); + verify(feedbackServiceMock).getFeedbackRequests(0L); + }); + } + } + + @Test() + void getFeedbackByPostTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + List<FeedbackDetails> feedbackDetailsList = new ArrayList<>(); + doReturn(feedbackDetailsList).when(feedbackServiceMock).getFeedbackRequests(2L); + // Act Statement(s) + String result = target.getFeedbackByPost(2L); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, + equalTo("{\"data\":[],\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getFeedbackRequests(2L); + }); + } + + @Test() + void getFeedbackByPostWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + List<FeedbackDetails> feedbackDetailsList = new ArrayList<>(); + doReturn(feedbackDetailsList).when(feedbackServiceMock).getFeedbackRequests(2L); + // Act Statement(s) + String result = target.getFeedbackByPost(2L); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, + equalTo("{\"data\":[],\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getFeedbackRequests(2L); + }); + } + + @Test() + void createFeedbackTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).saveFeedback("feedbackDetails1"); + // Act Statement(s) + String result = target.createFeedback("feedbackDetails1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).saveFeedback("feedbackDetails1"); + }); + } + + @Test() + void createFeedbackWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).saveFeedback("feedbackDetails1"); + // Act Statement(s) + String result = target.createFeedback("feedbackDetails1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).saveFeedback("feedbackDetails1"); + }); + } + + @Test() + void feedbacksListTest() throws Exception { + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + FeedbackDetails feedbackDetailsMock = mock(FeedbackDetails.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + doReturn(feedbackDetailsMock).when(inputMapperMock).fromJson("request1", FeedbackDetails.class); + doReturn(0L).when(feedbackDetailsMock).getBeneficiaryRegID(); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + List<FeedbackDetails> feedbackDetailsList = new ArrayList<>(); + doReturn(feedbackDetailsList).when(feedbackServiceMock).getFeedbackRequests(0L); + // Act Statement(s) + String result = target.feedbacksList("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":[],\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("request1", FeedbackDetails.class); + verify(feedbackDetailsMock).getBeneficiaryRegID(); + verify(feedbackServiceMock).getFeedbackRequests(0L); + }); + } + } + + @Test() + void feedbacksListWhenCaughtException() throws Exception { + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + FeedbackDetails feedbackDetailsMock = mock(FeedbackDetails.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + doReturn(feedbackDetailsMock).when(inputMapperMock).fromJson("request1", FeedbackDetails.class); + doReturn(0L).when(feedbackDetailsMock).getBeneficiaryRegID(); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + List<FeedbackDetails> feedbackDetailsList = new ArrayList<>(); + doReturn(feedbackDetailsList).when(feedbackServiceMock).getFeedbackRequests(0L); + // Act Statement(s) + String result = target.feedbacksList("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":[],\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("request1", FeedbackDetails.class); + verify(feedbackDetailsMock).getBeneficiaryRegID(); + verify(feedbackServiceMock).getFeedbackRequests(0L); + }); + } + } + + @Test() + void getFeedbackTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).getAllData("feedbackRequest1"); + // Act Statement(s) + String result = target.getFeedback("feedbackRequest1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getAllData("feedbackRequest1"); + }); + } + + @Test() + void getFeedbackWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).getAllData("feedbackRequest1"); + // Act Statement(s) + String result = target.getFeedback("feedbackRequest1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getAllData("feedbackRequest1"); + }); + } + + @Test() + void updateFeedbackTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn(2).when(feedbackServiceMock).updateFeedback("feedbackDetails1"); + // Act Statement(s) + String result = target.updateFeedback("feedbackDetails1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"2\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).updateFeedback("feedbackDetails1"); + }); + } + + @Test() + void updateFeedbackWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn(2).when(feedbackServiceMock).updateFeedback("feedbackDetails1"); + // Act Statement(s) + String result = target.updateFeedback("feedbackDetails1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"2\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).updateFeedback("feedbackDetails1"); + }); + } + + @Test() + void updateFeedbackStatusTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).updateFeedbackStatus(""); + // Act Statement(s) + String result = target.updateFeedbackStatus(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).updateFeedbackStatus(""); + }); + } + + @Test() + void updateFeedbackStatusWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).updateFeedbackStatus("D"); + // Act Statement(s) + String result = target.updateFeedbackStatus("D"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).updateFeedbackStatus("D"); + }); + } + + @Test() + void searchFeedbackTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).searchFeedback(""); + // Act Statement(s) + String result = target.searchFeedback(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).searchFeedback(""); + }); + } + + @Test() + void searchFeedbackWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).searchFeedback(""); + // Act Statement(s) + String result = target.searchFeedback(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).searchFeedback(""); + }); + } + + @Test() + void searchFeedback1Test() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).searchFeedback1(""); + // Act Statement(s) + String result = target.searchFeedback1(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).searchFeedback1(""); + }); + } + + @Test() + void searchFeedback1WhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).searchFeedback1(""); + // Act Statement(s) + String result = target.searchFeedback1(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).searchFeedback1(""); + }); + } + + @Test() + void getAllFeedbackByIdTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackRequestServiceMock).getAllFeedback(""); + // Act Statement(s) + String result = target.getAllFeedbackById(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackRequestServiceMock).getAllFeedback(""); + }); + } + + @Test() + void getAllFeedbackByIdWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackRequestServiceMock).getAllFeedback(""); + // Act Statement(s) + String result = target.getAllFeedbackById(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackRequestServiceMock).getAllFeedback(""); + }); + } + + // Sapient generated method id: ${b55f32b0-6608-3b68-9b57-67d5998a0e5f}, hash: + // C3E626822CB5A1BE9415B1569B6BA882 + @Test() + void getFeedbackStatusTypesTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).getFeedbackStatus("request1"); + // Act Statement(s) + String result = target.getFeedbackStatusTypes("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getFeedbackStatus("request1"); + }); + } + + // Sapient generated method id: ${10c23ab1-fb82-3597-9de6-2f93db0c3de4}, hash: + // 5AF7F0DE664008B140EBA8CEC974E6F5 + @Test() + void getFeedbackStatusTypesWhenCaughtException() throws Exception { + /* + * Branches:* (catch-exception (Exception)) : true** TODO: Help needed! This + * method is not unit testable!* Following variables could not be + * isolated/mocked: response* Suggestions:* You can pass them as constructor + * arguments or create a setter for them (avoid new operator)* or adjust the + * input/test parameter values manually to satisfy the requirements of the given + * test scenario.* The test code, including the assertion statements, has been + * successfully generated. + */ + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).getFeedbackStatus("request1"); + // Act Statement(s) + String result = target.getFeedbackStatusTypes("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getFeedbackStatus("request1"); + }); + } + + @Test() + void getEmailStatusTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).getEmailStatus("request1"); + // Act Statement(s) + String result = target.getEmailStatus("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getEmailStatus("request1"); + }); + } + + @Test() + void getEmailStatusWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("A").when(feedbackServiceMock).getEmailStatus("request1"); + // Act Statement(s) + String result = target.getEmailStatus("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).getEmailStatus("request1"); + }); + } + + @Test() + void getFeedbackRequestByIdTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackRequestServiceMock).getAllFeedback(""); + // Act Statement(s) + String result = target.getFeedbackRequestById(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackRequestServiceMock).getAllFeedback(""); + }); + } + + @Test() + void getFeedbackRequestByIdWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackRequestServiceMock).getAllFeedback(""); + // Act Statement(s) + String result = target.getFeedbackRequestById(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackRequestServiceMock).getAllFeedback(""); + }); + } + + @Test() + void getFeedbackResponseByIdTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackRequestServiceMock).getAllFeedback(""); + // Act Statement(s) + String result = target.getFeedbackResponseById(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackRequestServiceMock).getAllFeedback(""); + }); + } + + @Test() + void getFeedbackResponseByIdWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackRequestServiceMock).getAllFeedback(""); + // Act Statement(s) + String result = target.getFeedbackResponseById(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackRequestServiceMock).getAllFeedback(""); + }); + } + + @Test() + void getFeedbacksListTest() throws Exception { + // Arrange Statement(s) + HttpServletRequest httpRequestMock = mock(HttpServletRequest.class); + doReturn("return_of_getHeader1").when(httpRequestMock).getHeader("Authorization"); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + FeedbackListRequestModel feedbackListRequestModelMock = mock(FeedbackListRequestModel.class, + "getFeedbacksList_feedbackListRequestModel1"); + doReturn("A").when(feedbackServiceMock).getFeedbacksList(feedbackListRequestModelMock, "return_of_getHeader1"); + // Act Statement(s) + String result = target.getFeedbacksList(feedbackListRequestModelMock, httpRequestMock); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(httpRequestMock).getHeader("Authorization"); + verify(feedbackServiceMock).getFeedbacksList(feedbackListRequestModelMock, "return_of_getHeader1"); + }); + } + + @Test() + void getFeedbacksListWhenCaughtException() throws Exception { + // Arrange Statement(s) + HttpServletRequest httpRequestMock = mock(HttpServletRequest.class); + doReturn("return_of_getHeader1").when(httpRequestMock).getHeader("Authorization"); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + FeedbackListRequestModel feedbackListRequestModelMock = mock(FeedbackListRequestModel.class, + "getFeedbacksList_feedbackListRequestModel1"); + doReturn("A").when(feedbackServiceMock).getFeedbacksList(feedbackListRequestModelMock, "return_of_getHeader1"); + // Act Statement(s) + String result = target.getFeedbacksList(feedbackListRequestModelMock, httpRequestMock); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(httpRequestMock).getHeader("Authorization"); + verify(feedbackServiceMock).getFeedbacksList(feedbackListRequestModelMock, "return_of_getHeader1"); + }); + } + + @Test() + void updateResponseTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).updateResponse(""); + // Act Statement(s) + String result = target.updateResponse(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).updateResponse(""); + }); + } + + @Test() + void updateResponseWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).updateResponse(""); + // Act Statement(s) + String result = target.updateResponse(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).updateResponse(""); + }); + } + + // Sapient generated method id: ${8cf86177-2960-3ee0-9be1-9dc3529990d7}, hash: + // 7928D3E26A8757FC52D390C1CB7C9660 + @Test() + void requestFeedbackTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).createFeedbackRequest(""); + // Act Statement(s) + String result = target.requestFeedback(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).createFeedbackRequest(""); + }); + } + + @Test() + void requestFeedbackWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).createFeedbackRequest(""); + // Act Statement(s) + String result = target.requestFeedback(""); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).createFeedbackRequest(""); + }); + } + + @Test() + void getGrievancesByCreatedDateTest() throws Exception { + // Arrange Statement(s) + HttpServletRequest httpRequestMock = mock(HttpServletRequest.class); + doReturn("return_of_getHeader1").when(httpRequestMock).getHeader("Authorization"); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + FeedbackListRequestModel feedbackListRequestModelMock = mock(FeedbackListRequestModel.class, + "getGrievancesByCreatedDate_feedbackListRequestModel1"); + doReturn("A").when(feedbackServiceMock).getGrievancesByCreatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + // Act Statement(s) + String result = target.getGrievancesByCreatedDate(feedbackListRequestModelMock, httpRequestMock); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(httpRequestMock).getHeader("Authorization"); + verify(feedbackServiceMock).getGrievancesByCreatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + }); + } + + // Sapient generated method id: ${18b97990-90b1-3d8d-a4c1-cef12be9bc57}, hash: + // 3E15DAA476EEF73A0289776E75544FD7 + @Test() + void getGrievancesByCreatedDateWhenCaughtException() throws Exception { + /* + * Branches:* (catch-exception (Exception)) : true** TODO: Help needed! This + * method is not unit testable!* Following variables could not be + * isolated/mocked: response* Suggestions:* You can pass them as constructor + * arguments or create a setter for them (avoid new operator)* or adjust the + * input/test parameter values manually to satisfy the requirements of the given + * test scenario.* The test code, including the assertion statements, has been + * successfully generated. + */ + // Arrange Statement(s) + HttpServletRequest httpRequestMock = mock(HttpServletRequest.class); + doReturn("return_of_getHeader1").when(httpRequestMock).getHeader("Authorization"); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + FeedbackListRequestModel feedbackListRequestModelMock = mock(FeedbackListRequestModel.class, + "getGrievancesByCreatedDate_feedbackListRequestModel1"); + doReturn("A").when(feedbackServiceMock).getGrievancesByCreatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + // Act Statement(s) + String result = target.getGrievancesByCreatedDate(feedbackListRequestModelMock, httpRequestMock); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(httpRequestMock).getHeader("Authorization"); + verify(feedbackServiceMock).getGrievancesByCreatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + }); + } + + // Sapient generated method id: ${eafbf95c-ff4f-3081-897b-fc80540e62a5}, hash: + // E4B3306C1EA6B4CEFE0FA407E9BA780D + @Test() + void getGrievancesByUpdatedDateTest() throws Exception { + // Arrange Statement(s) + HttpServletRequest httpRequestMock = mock(HttpServletRequest.class); + doReturn("return_of_getHeader1").when(httpRequestMock).getHeader("Authorization"); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + FeedbackListRequestModel feedbackListRequestModelMock = mock(FeedbackListRequestModel.class, + "getGrievancesByUpdatedDate_feedbackListRequestModel1"); + doReturn("A").when(feedbackServiceMock).getGrievancesByUpdatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + // Act Statement(s) + String result = target.getGrievancesByUpdatedDate(feedbackListRequestModelMock, httpRequestMock); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(httpRequestMock).getHeader("Authorization"); + verify(feedbackServiceMock).getGrievancesByUpdatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + }); + } + + // Sapient generated method id: ${4fb8220a-ef79-3ab4-85c6-be5d27793fc2}, hash: + // 947A8D6C2D37A1E4B7255694C6F6B87C + @Test() + void getGrievancesByUpdatedDateWhenCaughtException() throws Exception { + /* + * Branches:* (catch-exception (Exception)) : true** TODO: Help needed! This + * method is not unit testable!* Following variables could not be + * isolated/mocked: response* Suggestions:* You can pass them as constructor + * arguments or create a setter for them (avoid new operator)* or adjust the + * input/test parameter values manually to satisfy the requirements of the given + * test scenario.* The test code, including the assertion statements, has been + * successfully generated. + */ + // Arrange Statement(s) + HttpServletRequest httpRequestMock = mock(HttpServletRequest.class); + doReturn("return_of_getHeader1").when(httpRequestMock).getHeader("Authorization"); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + FeedbackListRequestModel feedbackListRequestModelMock = mock(FeedbackListRequestModel.class, + "getGrievancesByUpdatedDate_feedbackListRequestModel1"); + doReturn("A").when(feedbackServiceMock).getGrievancesByUpdatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + // Act Statement(s) + String result = target.getGrievancesByUpdatedDate(feedbackListRequestModelMock, httpRequestMock); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"A\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(httpRequestMock).getHeader("Authorization"); + verify(feedbackServiceMock).getGrievancesByUpdatedDate(feedbackListRequestModelMock, + "return_of_getHeader1"); + }); + } + + // Sapient generated method id: ${9f527abd-8937-394a-8b33-cff4018923b7}, hash: + // A5EAFAE77C1EF099AC4E4AEDD101C48D + @Test() + void createFeedbackRequestTest() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).saveFeedbackRequest("A"); + // Act Statement(s) + String result = target.createFeedbackRequest("A"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).saveFeedbackRequest("A"); + }); + } + + @Test() + void createFeedbackRequestWhenCaughtException() throws Exception { + // Arrange Statement(s) + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).saveFeedbackRequest("D"); + // Act Statement(s) + String result = target.createFeedbackRequest("D"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + verify(feedbackServiceMock).saveFeedbackRequest("D"); + }); + } + + @Test() + void getFeedbackLogsTest() throws Exception { + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + FeedbackLog feedbackLogMock = mock(FeedbackLog.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + doReturn(feedbackLogMock).when(inputMapperMock).fromJson("A", FeedbackLog.class); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).getFeedbackLogs(feedbackLogMock); + // Act Statement(s) + String result = target.getFeedbackLogs("A"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("A", FeedbackLog.class); + verify(feedbackServiceMock).getFeedbackLogs(feedbackLogMock); + }); + } + } + + @Test() + void getFeedbackLogsWhenCaughtException() throws Exception { + + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + FeedbackLog feedbackLogMock = mock(FeedbackLog.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + doReturn(feedbackLogMock).when(inputMapperMock).fromJson("D", FeedbackLog.class); + target = new FeedbackController(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + doReturn("B").when(feedbackServiceMock).getFeedbackLogs(feedbackLogMock); + // Act Statement(s) + String result = target.getFeedbackLogs("D"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result, equalTo( + "{\"data\":{\"response\":\"B\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}")); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("D", FeedbackLog.class); + verify(feedbackServiceMock).getFeedbackLogs(feedbackLogMock); + }); + } + } + + @Test() + void feedbackRequestExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getFeedbackRequests(any())).thenThrow(NotFoundException.class); + + String response = target.feedbackRequest(request); + assertEquals(response, target.feedbackRequest(request)); + } + + @Test() + void getFeedbackByPostExpTest() { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getFeedbackRequests(any())).thenThrow(NotFoundException.class); + + String response = target.getFeedback(request); + assertEquals(response, target.getFeedback(request)); + } + + @Test() + void createFeedbackExpTest() throws Exception { + + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.saveFeedback(any())).thenThrow(NotFoundException.class); + + String response = target.createFeedback(request); + assertEquals(response, target.createFeedback(request)); + } + + @Test() + void feedbacksListExpTest() { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getFeedbackRequests(any())).thenThrow(NotFoundException.class); + + String response = target.feedbacksList(request); + assertEquals(response, target.feedbacksList(request)); + } + + @Test() + void updateFeedbackExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.updateFeedback(any())).thenThrow(NotFoundException.class); + + String response = target.updateFeedback(request); + assertEquals(response, target.updateFeedback(request)); + } + + @Test() + void updateFeedbackStatusExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.updateFeedbackStatus(any())).thenThrow(NotFoundException.class); + + String response = target.updateFeedbackStatus(request); + assertEquals(response, target.updateFeedbackStatus(request)); + } + + @Test() + void searchFeedbackExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.searchFeedback(any())).thenThrow(NotFoundException.class); + + String response = target.searchFeedback(request); + assertEquals(response, target.searchFeedback(request)); + } + + @Test() + void searchFeedback1ExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.searchFeedback1(any())).thenThrow(NotFoundException.class); + + String response = target.searchFeedback1(request); + assertEquals(response, target.searchFeedback1(request)); + } + + @Test() + void getAllFeedbackByIdExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackRequestServiceMock.getAllFeedback(any())).thenThrow(NotFoundException.class); + + String response = target.getAllFeedbackById(request); + assertEquals(response, target.getAllFeedbackById(request)); + } + + @Test() + void getFeedbackStatusTypesExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getFeedbackStatus(any())).thenThrow(NotFoundException.class); + + String response = target.getFeedbackStatusTypes(request); + assertEquals(response, target.getFeedbackStatusTypes(request)); + } + + @Test() + void getEmailStatusExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getEmailStatus(any())).thenThrow(NotFoundException.class); + + String response = target.getEmailStatus(request); + assertEquals(response, target.getEmailStatus(request)); + } + + @Test() + void getFeedbackRequestByIdExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackRequestServiceMock.getAllFeedback(any())).thenThrow(NotFoundException.class); + + String response = target.getFeedbackRequestById(request); + assertTrue(response.contains("Failed with null")); + // assertEquals(response, target.getFeedbackRequestById(request)); + } + + @Test() + void getFeedbackResponseByIdExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackRequestServiceMock.getAllFeedback(any())).thenThrow(NotFoundException.class); + + String response = target.getFeedbackResponseById(request); + assertEquals(response, target.getFeedbackResponseById(request)); + } + + @Test() + void getFeedbacksListExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getFeedbacksList(any(), any())).thenThrow(NotFoundException.class); + + String response = target.getFeedbacksList(any(), any()); + assertEquals(response, target.getFeedbacksList(any(), any())); + } + + @Test() + void updateResponseExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.updateResponse(any())).thenThrow(NotFoundException.class); + + String response = target.updateResponse(any()); + assertEquals(response, target.updateResponse(any())); + } + + @Test() + void requestFeedbackExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.createFeedbackRequest(any())).thenThrow(NotFoundException.class); + + String response = target.requestFeedback(any()); + assertTrue(response.contains("Failed with null")); +// assertEquals(response, target.requestFeedback(any())); + } + + @Test() + void getFeedbackSeverityExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackSeverityServiceMock.getActiveFeedbackSeverity(any()).toString()) + .thenThrow(NotFoundException.class); + + String response = target.getFeedbackSeverity(any()); + assertEquals(response, target.getFeedbackSeverity(any())); + } + + @Test() + void getFeedbackTypeExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackTypeServiceMock.getActiveFeedbackTypes(any())).thenThrow(NotFoundException.class); + + String response = target.getFeedbackType(any()); + assertEquals(response, target.getFeedbackType(any())); + } + + @Test() + void getGrievancesByCreatedDateExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getGrievancesByCreatedDate(any(), any())).thenThrow(NotFoundException.class); + + String response = target.getGrievancesByCreatedDate(any(), any()); + assertEquals(response, target.getGrievancesByCreatedDate(any(), any())); + } + + @Test() + void getGrievancesByUpdatedDateExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.getGrievancesByUpdatedDate(any(), any())).thenThrow(NotFoundException.class); + + String response = target.getGrievancesByUpdatedDate(any(), any()); + + assertTrue(response.contains("error")); + // assertEquals(response, target.getGrievancesByUpdatedDate(any(), any())); + } + + @Test() + void createFeedbackRequestExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.saveFeedbackRequest(any())).thenThrow(NotFoundException.class); + + String response = target.createFeedbackRequest(any()); + assertEquals(response, target.createFeedbackRequest(any())); + } + + @Test() + void getFeedbackLogsExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(feedbackServiceMock.saveFeedbackRequest(any())).thenThrow(NotFoundException.class); + + String response = target.getFeedbackLogs(any()); + assertEquals(response, target.getFeedbackLogs(any())); + } + + @Test + void testGetAllFeedbackReturnsCorrectJson() { + // Given + FeedbackResponse mockFeedbackResponse = new FeedbackResponse(); + mockFeedbackResponse.setFeedbackID(1L); + ArrayList<Object[]> mockedData = new ArrayList<>(); + mockedData.add(new Object[] { "Summary", 101, "Good", "John Doe", "Manager", 1, "SupSummary", null, + "Detailed Feedback" }); + + when(feedbackResponseServiceMock.getdataById(1L)).thenReturn(mockedData); + + // When + String result = target.getAllfeedback(mockFeedbackResponse); + + // Expected JSON + List<Map<String, Object>> expectedResList = new ArrayList<>(); + Map<String, Object> resMap = new HashMap<>(); + resMap.put("ResponseSummary", "Summary"); + resMap.put("FeedbackRequestID", 101); + resMap.put("Comments", "Good"); + resMap.put("AuthName", "John Doe"); + resMap.put("AuthDesignation", "Manager"); + resMap.put("FeedbackID", 1); + resMap.put("FeedbackSupSummary", "SupSummary"); + resMap.put("Feedback", "Detailed Feedback"); + expectedResList.add(resMap); + + Gson gson = new GsonBuilder().create(); + String expectedJson = gson.toJson(expectedResList); + + // Then + assertEquals(expectedJson, result); + + // Verify + verify(feedbackResponseServiceMock, times(1)).getdataById(1L); + } + + @Test + void testGetFeedbackByPostExceptionPath() { + Long feedbackID = 1L; + + // Simulate an exception when feedbackService.getFeedbackRequests is called + when(feedbackServiceMock.getFeedbackRequests(anyLong())).thenThrow(new RuntimeException("Test Exception")); + + // Execute the method that you're testing + String result = target.getFeedbackByPost(feedbackID); + + // Assert on the response + assertTrue(result.contains("error")); // Adjust this assertion based on how your OutputResponse.toString() is + } + +} diff --git a/src/test/java/com/iemr/common/controller/helpline104history/Helpline104BeneficiaryHistoryControllerTest.java b/src/test/java/com/iemr/common/controller/helpline104history/Helpline104BeneficiaryHistoryControllerTest.java new file mode 100644 index 00000000..65d34488 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/helpline104history/Helpline104BeneficiaryHistoryControllerTest.java @@ -0,0 +1,59 @@ +package com.iemr.common.controller.helpline104history; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.helpline104history.H104BenMedHistory; +import com.iemr.common.service.helpline104history.H104BenHistoryServiceImpl; +import com.iemr.common.utils.mapper.InputMapper; + +import jakarta.ws.rs.NotFoundException; + +@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) +@ExtendWith(MockitoExtension.class) +class Helpline104BeneficiaryHistoryControllerTest { + + private final H104BenHistoryServiceImpl smpleBenHistoryServiceImplMock = mock(H104BenHistoryServiceImpl.class, + "smpleBenHistoryServiceImpl"); + + private AutoCloseable autoCloseableMocks; + + @InjectMocks() + private Helpline104BeneficiaryHistoryController target; + + @AfterEach() + void afterTest() throws Exception { + if (autoCloseableMocks != null) + autoCloseableMocks.close(); + } + + @Test + void testGetBenCaseSheet_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(smpleBenHistoryServiceImplMock.geSmpleBenHistory(any()).toString()).thenThrow(NotFoundException.class); + + String response = target.getBenCaseSheet(request); + assertEquals(response, target.getBenCaseSheet(request)); + } +} diff --git a/src/test/java/com/iemr/common/controller/honeywell/HoneywellControllerTest.java b/src/test/java/com/iemr/common/controller/honeywell/HoneywellControllerTest.java new file mode 100644 index 00000000..127440f7 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/honeywell/HoneywellControllerTest.java @@ -0,0 +1,110 @@ +package com.iemr.common.controller.honeywell; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.service.honeywell.HoneywellService; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class HoneywellControllerTest { + + @InjectMocks + HoneywellController honeywellController; + + @Mock + private HoneywellService honeywellService; + + @Test + void testGetRealtimeDistrictWiseCallReport() throws Exception { + // String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(honeywellService.getRealtimeDistrictWiseCallReport()).thenReturn("any response"); + + // Execute the test + String actualResponse = honeywellController.getRealtimeDistrictWiseCallReport(); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + + } + + @Test + void testGetRealtimeDistrictWiseCallReport_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(honeywellService.getRealtimeDistrictWiseCallReport()).thenThrow(NotFoundException.class); + String response = honeywellController.getRealtimeDistrictWiseCallReport(); + assertEquals(response, honeywellController.getRealtimeDistrictWiseCallReport()); + } + + @Test + void testGetDistrictWiseCallReport() throws Exception { + String request = ""; + HttpServletRequest httpRequest = null; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(honeywellService.getDistrictWiseCallReport(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = honeywellController.getDistrictWiseCallReport(request, httpRequest); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + + } + + @Test + void testGetDistrictWiseCallReport_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest httpRequest = null; + when(honeywellService.getDistrictWiseCallReport(request)).thenThrow(NotFoundException.class); + String response = honeywellController.getDistrictWiseCallReport(request, httpRequest); + assertEquals(response, honeywellController.getDistrictWiseCallReport(request, httpRequest)); + } + + @Test + void testGetUrbanRuralCallReport() throws Exception { + String request = ""; + HttpServletRequest httpRequest = null; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(honeywellService.getUrbanRuralCallReport(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = honeywellController.getUrbanRuralCallReport(request, httpRequest); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + + } + + @Test + void testGetUrbanRuralCallReport_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + HttpServletRequest httpRequest = null; + when(honeywellService.getUrbanRuralCallReport(request)).thenThrow(NotFoundException.class); + String response = honeywellController.getUrbanRuralCallReport(request, httpRequest); + assertEquals(response, honeywellController.getUrbanRuralCallReport(request, httpRequest)); + + } +} diff --git a/src/test/java/com/iemr/common/controller/institute/InstituteControllerTest.java b/src/test/java/com/iemr/common/controller/institute/InstituteControllerTest.java new file mode 100644 index 00000000..f4cc8a0c --- /dev/null +++ b/src/test/java/com/iemr/common/controller/institute/InstituteControllerTest.java @@ -0,0 +1,150 @@ +package com.iemr.common.controller.institute; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.when; + +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.institute.Institute; +import com.iemr.common.service.institute.DesignationService; +import com.iemr.common.service.institute.InstituteService; +import com.iemr.common.service.institute.InstituteTypeService; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class InstituteControllerTest { + + @Mock + private InputMapper inputMapper; + + @Mock + private InstituteService instituteService; + + @Mock + private InstituteTypeService instituteTypeService; + + @Mock + private DesignationService designationService; + + @InjectMocks + private InstituteController instituteController; // Replace "YourClass" with the actual class name + + @Test + void testGetInstituteTypes() throws Exception { + String instituteTypeRequest = "{\"providerServiceMapID\": \"1\"}"; + + OutputResponse response = new OutputResponse(); + + response.setResponse(instituteTypeService.getInstitutionTypes(instituteTypeRequest).toString()); + + String expRes = instituteController.getInstituteTypes(instituteTypeRequest); + + assertTrue(expRes.contains("Success")); + } + + @Test + void testGetInstituteTypes_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(instituteTypeService.getInstitutionTypes(request).toString()).thenThrow(NotFoundException.class); + String response = instituteController.getInstituteTypes(request); + assertEquals(response, instituteController.getInstituteTypes(request)); + } + + @Test + void testGetInstituteName() throws Exception { + Integer institutionTypeID = 1; + OutputResponse response = new OutputResponse(); + + response.setResponse(instituteTypeService.getInstitutionName(institutionTypeID).toString()); + + String expRes = instituteController.getInstituteName(institutionTypeID); + + assertTrue(expRes.contains("Success")); + } + + @Test + void testGetInstituteName_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(instituteTypeService.getInstitutionName(any()).toString()).thenThrow(NotFoundException.class); + + String response = instituteController.getInstituteName(any()); + assertEquals(response, instituteController.getInstituteName(any())); + } + + @Test + void testGetDesignations() { + OutputResponse response = new OutputResponse(); + + response.setResponse(designationService.getDesignations().toString()); + + String expRes = instituteController.getDesignations(); + + assertTrue(expRes.contains("Success")); + } + + @Test + void testGetDesignations_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(designationService.getDesignations().toString()).thenThrow(NotFoundException.class); + + String response = instituteController.getDesignations(); + assertEquals(response, instituteController.getDesignations()); + } + + @Test + void testGetInstituteNameByTypeAndDistrict() throws Exception { + Integer institutionTypeID = 1; + Integer districtID = 1; + + OutputResponse response = new OutputResponse(); + + response.setResponse( + instituteTypeService.getInstitutionNameByTypeAndDistrict(institutionTypeID, districtID).toString()); + + String expRes = instituteController.getInstituteNameByTypeAndDistrict(institutionTypeID, districtID); + + assertTrue(expRes.contains("Success")); + } + + @Test + void testGetInstituteNameByTypeAndDistrict_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(instituteTypeService.getInstitutionNameByTypeAndDistrict(any(), any()).toString()) + .thenThrow(NotFoundException.class); + + String response = instituteController.getInstituteNameByTypeAndDistrict(any(), any()); + assertEquals(response, instituteController.getInstituteNameByTypeAndDistrict(any(), any())); + } + + @Test() + void getInstituteByBranchExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + String response = instituteController.getInstituteByBranch(request); + assertEquals(response, instituteController.getInstituteByBranch(request)); + } + + @Test() + void getInstitutesByLocationExpTest() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + String response = instituteController.getInstitutesByLocation(request); + assertEquals(response, instituteController.getInstitutesByLocation(request)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/kmfilemanager/KMFileManagerControllerTest.java b/src/test/java/com/iemr/common/controller/kmfilemanager/KMFileManagerControllerTest.java new file mode 100644 index 00000000..ee713936 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/kmfilemanager/KMFileManagerControllerTest.java @@ -0,0 +1,84 @@ +package com.iemr.common.controller.kmfilemanager; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.data.kmfilemanager.KMFileManager; +import com.iemr.common.service.kmfilemanager.KMFileManagerService; +import com.iemr.common.service.scheme.SchemeServiceImpl; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class KMFileManagerControllerTest { + + @InjectMocks + KMFileManagerController kmFileManagerController; + + @Mock + private KMFileManagerService kmFileManagerService; + + @Mock + private InputMapper inputMapper; + + @Mock + private SchemeServiceImpl schemeServiceImpl; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void addFileSuccess() throws Exception { + // Local setup for this test + String addFileRequestJson = "{\"fileName\":\"test.pdf\", \"fileExtension\":\"pdf\", \"providerServiceMapID\":\"1\", \"userID\":\"2\", \"validFrom\":\"1633036800\", \"validUpto\":\"1635638800\", \"fileContent\":\"base64EncodedString==\", \"createdBy\":\"user\", \"categoryID\":\"1\", \"subCategoryID\":\"2\"}"; + String expectedResponse = "Success Response"; + when(kmFileManagerService.addKMFile(anyString())).thenReturn(expectedResponse); + + // Execution + String actualResponse = kmFileManagerService.addKMFile(addFileRequestJson); + + // Assertion + assertTrue(actualResponse.contains(expectedResponse)); + + // Verification + verify(kmFileManagerService).addKMFile(anyString()); + } + + @Test + void getKMFileDownloadURL_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + // when(schemeServiceImpl.getFilePath(any())).thenThrow(NotFoundException.class); + + String response = kmFileManagerController.getKMFileDownloadURL(request); + // assertEquals(response, kmFileManagerController.addFile(request)); + } + + @Test + void addFile_exp() throws NoSuchAlgorithmException, IOException, IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(kmFileManagerService.addKMFile(request)).thenThrow(NotFoundException.class); + + String response = kmFileManagerController.addFile(request); + assertTrue(response.contains("Failed with null")); + } + +} diff --git a/src/test/java/com/iemr/common/controller/language/LanguageControllerTest.java b/src/test/java/com/iemr/common/controller/language/LanguageControllerTest.java new file mode 100644 index 00000000..28778c27 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/language/LanguageControllerTest.java @@ -0,0 +1,66 @@ +package com.iemr.common.controller.language; + +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.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.userbeneficiarydata.Language; +import com.iemr.common.service.userbeneficiarydata.LanguageService; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class LanguageControllerTest { + + @InjectMocks + private LanguageController languageController; + + @Mock + private LanguageService languageService; + + @Test + void testGetLanguageListSuccess() { + // Prepare mocked data + + Language language1 = new Language(1, "English", "ENG", "a", "b"); + Language language2 = new Language(2, "Spanish", "SPA", "a", "b"); + List<Language> mockLanguageList = Arrays.asList(language1, language2); + + // Mock the service's response + when(languageService.getActiveLanguages()).thenReturn(mockLanguageList); + + // Execute the controller method + String response = languageController.getLanguageList(); + + // Assertions + assertNotNull(response); + assertTrue(response.contains("English")); + assertTrue(response.contains("Spanish")); + + // Verify the service was called once + verify(languageService).getActiveLanguages(); + } + + @Test + void getCategoriesTest_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(languageService.getActiveLanguages().toString()).thenThrow(NotFoundException.class); + + String response = languageController.getLanguageList(); + + assertTrue(response.contains("Failed with null")); + } + +} diff --git a/src/test/java/com/iemr/common/controller/location/LocationControllerTest.java b/src/test/java/com/iemr/common/controller/location/LocationControllerTest.java new file mode 100644 index 00000000..27064033 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/location/LocationControllerTest.java @@ -0,0 +1,336 @@ +package com.iemr.common.controller.location; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.iemr.common.data.location.Country; +import com.iemr.common.data.location.DistrictBlock; +import com.iemr.common.data.location.DistrictBranchMapping; +import com.iemr.common.data.location.Districts; +import com.iemr.common.data.location.States; +import com.iemr.common.service.location.LocationService; + +@ExtendWith(SpringExtension.class) +class LocationControllerTest { + + @Mock + private LocationService locationService; + + @Mock + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @InjectMocks + private LocationController locationController; + + @Test + void testGetStates_Success() throws Exception { + // Local setup + States state1 = new States(); + state1.setStateID(1); + state1.setStateName("TestState1"); + state1.setCountryID(1); + + States state2 = new States(); + state2.setStateID(2); + state2.setStateName("TestState2"); + state2.setCountryID(1); + + int countryId = 1; + List<States> statesList = Arrays.asList(state1, state2); + + // Mocking + when(locationService.getStates(countryId)).thenReturn(statesList); + + // Execution + String response = locationController.getStates(countryId); + + // Assertions + assertNotNull(response); + assertTrue(response.contains("TestState1")); + assertTrue(response.contains("TestState2")); + + // Verification + verify(locationService, times(1)).getStates(countryId); + } + + + @Test + void testGetDistricts_Success() throws Exception { + // Local setup + Districts district1 = new Districts(); + district1.setDistrictID(1); + district1.setDistrictName("District1"); + district1.setStateID(1); + + Districts district2 = new Districts(); + district2.setDistrictID(2); + district2.setDistrictName("District2"); + district2.setStateID(1); + + int stateId = 1; + List<Districts> districtsList = Arrays.asList(district1, district2); + + // Mocking + when(locationService.getDistricts(stateId)).thenReturn(districtsList); + + // Execution + String response = locationController.getDistricts(stateId); + + // Assertions + assertNotNull(response); + assertTrue(response.contains("District1")); + assertTrue(response.contains("District2")); + + // Verification + verify(locationService, times(1)).getDistricts(stateId); + } + + + @Test + void testGetStateDistrictsSuccess() { + // Given + int stateId = 1; + Districts district1 = new Districts(); // Assuming Districts is properly defined elsewhere + district1.setDistrictID(1); + district1.setDistrictName("District1"); + district1.setStateID(stateId); + + Districts district2 = new Districts(); + district2.setDistrictID(2); + district2.setDistrictName("District2"); + district2.setStateID(stateId); + + List<Districts> mockDistrictsList = Arrays.asList(district1, district2); + when(locationService.findStateDistrictBy(stateId)).thenReturn(mockDistrictsList); + + // When + String response = locationController.getStatetDistricts(stateId); + + // Then + assertNotNull(response); + assertTrue(response.contains("District1")); + assertTrue(response.contains("District2")); + + // Verify that the service method was called once + verify(locationService).findStateDistrictBy(stateId); + } + + + @Test + void testGetDistrictBlocksSuccess() { + // Given + int districtId = 10; + DistrictBlock block1 = new DistrictBlock(); // Assuming DistrictBlock is properly defined elsewhere + block1.setBlockID(101); + block1.setBlockName("Block1"); + block1.setDistrictID(districtId); + + DistrictBlock block2 = new DistrictBlock(); + block2.setBlockID(102); + block2.setBlockName("Block2"); + block2.setDistrictID(districtId); + + List<DistrictBlock> mockBlockList = Arrays.asList(block1, block2); + when(locationService.getDistrictBlocks(districtId)).thenReturn(mockBlockList); + + // When + String response = locationController.getDistrictBlocks(districtId); + + // Then + assertNotNull(response); + assertTrue(response.contains("Block1")); + assertTrue(response.contains("Block2")); + + // Verify that the service method was called once + verify(locationService).getDistrictBlocks(districtId); + } + + + + @Test + void testGetCitySuccess() { + // Given + int districtId = 1; + DistrictBlock block1 = new DistrictBlock(); // Assuming DistrictBlock is a valid class + block1.setBlockID(1); + block1.setBlockName("City1"); + block1.setDistrictID(districtId); + + DistrictBlock block2 = new DistrictBlock(); + block2.setBlockID(2); + block2.setBlockName("City2"); + block2.setDistrictID(districtId); + + List<DistrictBlock> mockDistrictBlockList = Arrays.asList(block1, block2); + when(locationService.getDistrictBlocks(districtId)).thenReturn(mockDistrictBlockList); + + // When + String response = locationController.getCity(districtId); + + // Then + assertNotNull(response); + assertTrue(response.contains("City1")); + assertTrue(response.contains("City2")); + + // Verify that the service method was called once + verify(locationService).getDistrictBlocks(districtId); + } + + + @Test + void testGetVillagesSuccess() { + // Given + int districtId = 1; + DistrictBranchMapping village1 = new DistrictBranchMapping(); // Assuming a valid class exists + village1.setBlockID(1); + village1.setVillageName("Village1"); + village1.setDistrictBranchID(districtId); + + DistrictBranchMapping village2 = new DistrictBranchMapping(); + village2.setBlockID(2); + village2.setVillageName("Village2"); + village2.setDistrictBranchID(districtId); + + List<DistrictBranchMapping> mockVillageList = Arrays.asList(village1, village2); + when(locationService.getDistrilctBranchs(districtId)).thenReturn(mockVillageList); + + // When + String response = locationController.getVillages(districtId); + + // Then + assertNotNull(response); + assertTrue(response.contains("Village1")); + assertTrue(response.contains("Village2")); + + // Verify that the service method was called once + verify(locationService).getDistrilctBranchs(districtId); + } + + + @Test + void testGetCountriesSuccess() { + // Given + Country country1 = new Country(); // Assuming a valid Country class exists + country1.setCountryID(1); + country1.setCountryName("Country1"); + country1.setCountryCode("1"); + + Country country2 = new Country(); + country2.setCountryID(2); + country2.setCountryName("Country2"); + country2.setCountryCode("2"); + + List<Country> mockCountryList = Arrays.asList(country1, country2); + when(locationService.getCountries()).thenReturn(mockCountryList); + + // When + String response = locationController.getCountries(); + + // Then + assertNotNull(response); + assertTrue(response.contains("Country1")); + assertTrue(response.contains("Country2")); + + // Verify that the service method was called once + verify(locationService).getCountries(); + } + + @Test + void testGetStatesException() { + Integer id = 1; + RuntimeException exception = new RuntimeException("Test exception"); + + doThrow(exception).when(locationService).getStates(id); + + String result = locationController.getStates(id); + + assertTrue(result.contains("error")); // Adjust assertion based on actual output format + } + + @Test + void testGetDistrictsException() { + int testId = 1; + Exception simulatedException = new RuntimeException("Simulated exception"); + + doThrow(simulatedException).when(locationService).getDistricts(testId); + + String result = locationController.getDistricts(testId); + + assertTrue(result.contains(simulatedException.getMessage())); + } + + @Test + void testGetStateDistrictsExceptionHandling() { + int testId = 1; + String simulatedErrorMessage = "Simulated error"; + Exception simulatedException = new RuntimeException(simulatedErrorMessage); + + doThrow(simulatedException).when(locationService).findStateDistrictBy(testId); + + String result = locationController.getStatetDistricts(testId); + + assertTrue(result.contains("error")); // This assumes your OutputResponse's toString method will output + // something that can be checked for "error" + } + + @Test + void testGetDistrictBlocksExceptionHandling() { + int testId = 1; + Exception simulatedException = new RuntimeException("Simulated exception for test"); + + doThrow(simulatedException).when(locationService).getDistrictBlocks(testId); + + String result = locationController.getDistrictBlocks(testId); + + assertTrue(result.contains("error") || result.contains(simulatedException.getMessage())); + } + + @Test + void testGetCityExceptionHandling() { + int testId = 1; + Exception simulatedException = new RuntimeException("Simulated exception"); + + doThrow(simulatedException).when(locationService).getDistrictBlocks(testId); + + String result = locationController.getCity(testId); + assertTrue(result.contains("error") || result.contains(simulatedException.getMessage())); + } + + @Test + void testGetCountriesExceptionHandling() { + Exception simulatedException = new RuntimeException("Simulated exception"); + doThrow(simulatedException).when(locationService).getCountries(); + + String result = locationController.getCountries(); + // logging + assertTrue(result.contains("error") || result.contains(simulatedException.getMessage())); + } + + @Test + void testGetVillagesExceptionHandling() { + int testId = 1; + Exception simulatedException = new RuntimeException("Simulated exception"); + + doThrow(simulatedException).when(locationService).getDistrilctBranchs(testId); + + String result = locationController.getVillages(testId); + + assertTrue(result.contains("error") || result.contains(simulatedException.getMessage())); + } + +} diff --git a/src/test/java/com/iemr/common/controller/lonic/LonicControllerTest.java b/src/test/java/com/iemr/common/controller/lonic/LonicControllerTest.java new file mode 100644 index 00000000..7ed1ce6e --- /dev/null +++ b/src/test/java/com/iemr/common/controller/lonic/LonicControllerTest.java @@ -0,0 +1,71 @@ +package com.iemr.common.controller.lonic; + +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.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.lonic.LonicDescription; +import com.iemr.common.service.lonic.LonicService; + +@ExtendWith(MockitoExtension.class) +class LonicControllerTest { + + @InjectMocks + LonicController lonicController; + + @Mock + private LonicService lonicService; + + @Test + void getLonicRecordListSuccess() throws Exception { + // Arrange + String requestJson = "{\"term\":\"testTerm\",\"pageNo\":1}"; + String expectedResponse = "[{\"id\":\"1\",\"description\":\"Test Description\"}]"; + when(lonicService.findLonicRecordList(any(LonicDescription.class))).thenReturn(expectedResponse); + + // Act + String result = lonicController.getLonicRecordList(requestJson); + + // Assert + assertNotNull(result, "The result should not be null."); + assertTrue(result.contains(expectedResponse), "The result should contain the expected response."); + } + + @Test + void getLonicRecordListNoRecordsFound() throws Exception { + // Arrange + String requestJson = "{\"term\":\"unknownTerm\",\"pageNo\":1}"; + when(lonicService.findLonicRecordList(any(LonicDescription.class))).thenReturn(null); // Simulating no records + // found + + // Act + String result = lonicController.getLonicRecordList(requestJson); + + // Assert + assertNotNull(result, "The result should not be null."); + assertTrue(result.contains("No Records Found"), "The result should indicate no records were found."); + } + + @Test + void getLonicRecordListException() throws Exception { + // Arrange + String requestJson = "{\"term\":\"testTerm\",\"pageNo\":1}"; + when(lonicService.findLonicRecordList(any(LonicDescription.class))) + .thenThrow(new RuntimeException("Test exception")); + + // Act + String result = lonicController.getLonicRecordList(requestJson); + + // Assert + assertNotNull(result, "The result should not be null."); + assertTrue(result.contains("error"), "The result should contain error information."); + } + +} diff --git a/src/test/java/com/iemr/common/controller/lungassessment/LungAssessmentControllerTest.java b/src/test/java/com/iemr/common/controller/lungassessment/LungAssessmentControllerTest.java new file mode 100644 index 00000000..57eda5d6 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/lungassessment/LungAssessmentControllerTest.java @@ -0,0 +1,122 @@ +package com.iemr.common.controller.lungassessment; + +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.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import com.iemr.common.service.lungassessment.LungAssessmentService; + +@ExtendWith(MockitoExtension.class) +class LungAssessmentControllerTest { + @Mock + private LungAssessmentService lungAssessmentService; + + @InjectMocks + private LungAssessmentController lungAssessmentController; + + + @Test + void testStartAssessmentSuccess() throws Exception { + // Arrange + String requestJson = "{\"patientId\":\"12345\"}"; + MultipartFile file = new MockMultipartFile("file", "test.txt", "text/plain", + "This is a dummy file content".getBytes()); + when(lungAssessmentService.initiateAssesment(any(String.class), any(MultipartFile.class))) + .thenReturn("Assessment started successfully"); + + // Act + String result = lungAssessmentController.startAssesment(file, requestJson); + + // Assert + assertNotNull(result); + assertTrue(result.contains("Assessment started successfully")); + } + + + @Test + void testGetAssessmentSuccess() throws Exception { + // Arrange + String assessmentId = "123"; // Example assessment ID + String expectedResult = "Assessment details"; // Example response from the service + when(lungAssessmentService.getAssesment(assessmentId)).thenReturn(expectedResult); + + // Act + String actualResult = lungAssessmentController.getAssessment(assessmentId.toString()); + + // Assert + assertNotNull(actualResult); + assertTrue(actualResult.contains(expectedResult), + "The response should contain the assessment details returned by the service."); + } + + + @Test + void getAssessmentDetailsSuccess() throws Exception { + // Arrange + Long patientId = 1L; // Example patient ID + String serviceResponse = "Assessment Detail"; // Mocked service layer response + when(lungAssessmentService.getAssessmentDetails(patientId)).thenReturn(serviceResponse); + + // Act + String result = lungAssessmentController.getAssessmentDetails(patientId); + + // Assert + assertNotNull(result, "The result should not be null."); + assertTrue(result.contains(serviceResponse), "The result should contain the service response."); + } + + @Test + void startAssesmentTest_ExceptionThrown() throws Exception { + // Mocking the file and request + MultipartFile file = new MockMultipartFile("file", "filename.txt", "text/plain", "some xml".getBytes()); + String request = "someRequestData"; + + // Simulating an exception during the call to initiateAssesment + doThrow(new RuntimeException("Test exception")).when(lungAssessmentService).initiateAssesment(request, file); + + // Call the method under test + String response = lungAssessmentController.startAssesment(file, request); + + verify(lungAssessmentService).initiateAssesment(request, file); + } + + @Test + void getAssessment_ExceptionThrown() throws Exception { + // Given + String assessmentId = "testAssessmentId"; + doThrow(new RuntimeException("Test exception")).when(lungAssessmentService).getAssesment(assessmentId); + + // When + String response = lungAssessmentController.getAssessment(assessmentId); + + // Then + // Verify that the service method was called + verify(lungAssessmentService).getAssesment(assessmentId); + } + + @Test + void getAssessmentDetails_ExceptionThrown() throws Exception { + // Setup + Long patientId = 1L; + RuntimeException expectedException = new RuntimeException("Test exception"); + doThrow(expectedException).when(lungAssessmentService).getAssessmentDetails(patientId); + + // Execution + String response = lungAssessmentController.getAssessmentDetails(patientId); + + // Verification + verify(lungAssessmentService).getAssessmentDetails(patientId); + + } +} diff --git a/src/test/java/com/iemr/common/controller/mctshistory/OutboundHistoryControllerTest.java b/src/test/java/com/iemr/common/controller/mctshistory/OutboundHistoryControllerTest.java new file mode 100644 index 00000000..f3201676 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/mctshistory/OutboundHistoryControllerTest.java @@ -0,0 +1,87 @@ +package com.iemr.common.controller.mctshistory; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.iemr.common.service.mctshistory.OutboundHistoryService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class OutboundHistoryControllerTest { + + @InjectMocks + OutboundHistoryController outboundHistoryController; + + @Mock + private OutboundHistoryService outboundHistoryService; + + @Test + void testGetCallHistory() throws IEMRException, JsonMappingException, JsonProcessingException { + + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); + + when(outboundHistoryService.getCallHistory(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = outboundHistoryController.getCallHistory(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testGetCallHistory_Exception() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(outboundHistoryService.getCallHistory(request)).thenThrow(NotFoundException.class); + + String response = outboundHistoryController.getCallHistory(request); + assertTrue(response.contains("Failed with null")); + //assertEquals(response, outboundHistoryController.getCallHistory(request)); + } + + @Test + void testGetMctsCallResponse() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); + + when(outboundHistoryService.getMctsCallResponse(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = outboundHistoryController.getMctsCallResponse(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + + } + + @Test + void testGetMctsCallResponse_Exception() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(outboundHistoryService.getMctsCallResponse(request)).thenThrow(NotFoundException.class); + + String response = outboundHistoryController.getMctsCallResponse(request); + assertEquals(response, outboundHistoryController.getMctsCallResponse(request)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/nhmdashboard/NHMDetailCallReportSchedulerTest.java b/src/test/java/com/iemr/common/controller/nhmdashboard/NHMDetailCallReportSchedulerTest.java new file mode 100644 index 00000000..0c12ee6b --- /dev/null +++ b/src/test/java/com/iemr/common/controller/nhmdashboard/NHMDetailCallReportSchedulerTest.java @@ -0,0 +1,78 @@ +package com.iemr.common.controller.nhmdashboard; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +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 java.sql.Timestamp; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.util.ReflectionTestUtils; + +import com.iemr.common.data.nhm_dashboard.DetailedCallReport; +import com.iemr.common.repository.nhm_dashboard.DetailedCallReportRepo; +import com.iemr.common.repository.report.CallReportRepo; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class NHMDetailCallReportSchedulerTest { + + @Mock + private DetailedCallReportRepo detailedCallReportRepo; + + @Mock + private CallReportRepo callReportRepo; + + @InjectMocks + private NHMDetailCallReportScheduler scheduler; + + @Value("${start-ctidatacheck-scheduler}") + private boolean startCtiDataCheckFlag = true; // Assuming this is how you would like to inject values for testing + // purposes + + @Test + void testDetailedCallReportSchedulerEnabledAndRecordsFound() { + // Use ReflectionTestUtils to set the private field value + ReflectionTestUtils.setField(scheduler, "startCtiDataCheckFlag", true); + + DetailedCallReport report = new DetailedCallReport(); // Set necessary fields + report.setSession_ID("session1"); + report.setPHONE("1234567890"); + List<DetailedCallReport> reports = Collections.singletonList(report); + + when(detailedCallReportRepo.findByCallStartTimeBetween(any(Timestamp.class), any(Timestamp.class))) + .thenReturn(reports); + when(callReportRepo.getBenCallDetailsBySessionIDAndPhone(anyString(), anyString())).thenReturn(1); + + // When + scheduler.detailedCallReport(); + + // Then + verify(callReportRepo, times(1)).getBenCallDetailsBySessionIDAndPhone(anyString(), anyString()); + } + + @Test + void testDetailedCallReportSchedulerDisabled() { + // Given + this.startCtiDataCheckFlag = false; // Directly set the flag to false or use a setter method + + // When + scheduler.detailedCallReport(); + + // Then + verify(detailedCallReportRepo, never()).findByCallStartTimeBetween(any(Timestamp.class), any(Timestamp.class)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/nhmdashboard/NationalHealthMissionDashboardControllerTest.java b/src/test/java/com/iemr/common/controller/nhmdashboard/NationalHealthMissionDashboardControllerTest.java new file mode 100644 index 00000000..50523426 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/nhmdashboard/NationalHealthMissionDashboardControllerTest.java @@ -0,0 +1,127 @@ +package com.iemr.common.controller.nhmdashboard; + +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.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.nhm_dashboard.AbandonCallSummary; +import com.iemr.common.service.nhm_dashboard.NHM_DashboardService; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class NationalHealthMissionDashboardControllerTest { + + @InjectMocks + NationalHealthMissionDashboardController nationalHealthMissionDashboardController; + + @Mock + private NHM_DashboardService nHM_DashboardService; + + @Test + void testPushAbandonCallsSuccess() throws Exception { + // Arrange + AbandonCallSummary abandonCallSummary = new AbandonCallSummary(); // mock or create instance as required + when(nHM_DashboardService.pushAbandonCalls(abandonCallSummary)).thenReturn("Success response"); + + // Act + String result = nationalHealthMissionDashboardController.pushAbandonCallsFromC_Zentrix(abandonCallSummary); + + // Assert + assertNotNull(result); + assertTrue(result.contains("Success response")); + } + + + @Test + void testGetAbandonCallsSuccess() throws Exception { + // Arrange + String expectedResponse = "Mocked abandon calls response"; + when(nHM_DashboardService.getAbandonCalls()).thenReturn(expectedResponse); + + // Act + String result = nationalHealthMissionDashboardController.getAbandonCalls(); + + // Assert + assertNotNull(result); + assertTrue(result.contains(expectedResponse)); + } + + + @Test + void testGetAgentSummaryReport_Success() throws Exception { + // Arrange + String expectedResponse = "Mocked Agent Summary Report"; + when(nHM_DashboardService.getAgentSummaryReport()).thenReturn(expectedResponse); + + // Act + String result = nationalHealthMissionDashboardController.getAgentSummaryReport(); + + // Assert + assertNotNull(result); + assertTrue(result.contains(expectedResponse)); + } + + @Test + void testGetDetailedCallReport_Success() throws Exception { + // Arrange + String expectedResponse = "Mocked Detailed Call Report"; + when(nHM_DashboardService.getDetailedCallReport()).thenReturn(expectedResponse); + + // Act + String result = nationalHealthMissionDashboardController.getDetailedCallReport(); + + // Assert + assertNotNull(result); + assertTrue(result.contains(expectedResponse)); + } + + @Test + void pushAbandonCallsFromC_Zentrix_exp() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(nHM_DashboardService.pushAbandonCalls(any())).thenThrow(NotFoundException.class); + + String response = nationalHealthMissionDashboardController.pushAbandonCallsFromC_Zentrix(any()); + assertEquals(response, nationalHealthMissionDashboardController.pushAbandonCallsFromC_Zentrix(any())); + } + + @Test + void getAbandonCalls_exp() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(nHM_DashboardService.getAbandonCalls()).thenThrow(NotFoundException.class); + + String response = nationalHealthMissionDashboardController.getAbandonCalls(); + assertEquals(response, nationalHealthMissionDashboardController.getAbandonCalls()); + } + + @Test + void getAgentSummaryReport_exp() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(nHM_DashboardService.getAgentSummaryReport()).thenThrow(NotFoundException.class); + + String response = nationalHealthMissionDashboardController.getAgentSummaryReport(); + assertEquals(response, nationalHealthMissionDashboardController.getAgentSummaryReport()); + } + + @Test + void getDetailedCallReport_exp() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(nHM_DashboardService.getDetailedCallReport()).thenThrow(NotFoundException.class); + + String response = nationalHealthMissionDashboardController.getDetailedCallReport(); + assertEquals(response, nationalHealthMissionDashboardController.getDetailedCallReport()); + } + +} diff --git a/src/test/java/com/iemr/common/controller/notification/NotificationControllerTest.java b/src/test/java/com/iemr/common/controller/notification/NotificationControllerTest.java new file mode 100644 index 00000000..ae00df78 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/notification/NotificationControllerTest.java @@ -0,0 +1,342 @@ +package com.iemr.common.controller.notification; + +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 java.io.IOException; +import java.security.NoSuchAlgorithmException; + +import org.json.JSONException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.iemr.common.service.notification.NotificationService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class NotificationControllerTest { + + @InjectMocks + private NotificationController notificationController; + + @Mock + private NotificationService notificationService; + + @Test + void testGetNotification() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.getNotification(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.getNotification(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + + } + + @Test + void testGetNotificationException() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.getNotification(request)).thenThrow(NotFoundException.class); + + String response = notificationController.getNotification(request); + assertEquals(response, notificationController.getNotification(request)); + } + + @Test + void testGetSupervisorNotification() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.getSupervisorNotification(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.getSupervisorNotification(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testGetSupervisorNotification_Exception() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.getSupervisorNotification(request)).thenThrow(NotFoundException.class); + + String response = notificationController.getSupervisorNotification(request); + assertEquals(response, notificationController.getSupervisorNotification(request)); + } + + @Test + void testCreateNotification() throws NoSuchAlgorithmException, IOException, IEMRException, Exception { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.createNotification(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.createNotification(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testCreateNotification_Exception() throws NoSuchAlgorithmException, IOException, IEMRException, Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.createNotification(request)).thenThrow(NotFoundException.class); + + String response = notificationController.createNotification(request); + assertEquals(response, notificationController.createNotification(request)); + } + + @Test + void testUpdateNotification() + throws NoSuchAlgorithmException, JSONException, IOException, IEMRException, Exception { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.updateNotification(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.updateNotification(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testUpdateNotification_Exception() + throws NoSuchAlgorithmException, JSONException, IOException, IEMRException, Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.updateNotification(request)).thenThrow(NotFoundException.class); + + String response = notificationController.updateNotification(request); + assertEquals(response, notificationController.updateNotification(request)); + } + + @Test + void testGetNotificationType() throws IEMRException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.getNotificationType(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.getNotificationType(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testGetNotificationType_Exception() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.getNotificationType(request)).thenThrow(NotFoundException.class); + + String response = notificationController.getNotificationType(request); + assertEquals(response, notificationController.getNotificationType(request)); + } + + @Test + void testCreateNotificationType() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.createNotificationType(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.createNotificationType(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testCreateNotificationType_Exception() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + //when(notificationService.getNotificationType(request)).thenThrow(NotFoundException.class); + + String response = notificationController.createNotificationType(request); + assertEquals(response, notificationController.createNotificationType(request)); + } + + @Test + void testUpdateNotificationType() throws JSONException, IEMRException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.updateNotificationType(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.updateNotificationType(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testUpdateNotificationType_Exception() throws JSONException, IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.updateNotificationType(request)).thenThrow(NotFoundException.class); + + String response = notificationController.updateNotificationType(request); + assertEquals(response, notificationController.updateNotificationType(request)); + } + + @Test + void testGetEmergencyContacts() throws IEMRException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.getEmergencyContacts(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.getEmergencyContacts(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testGetEmergencyContacts_Exception() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.getEmergencyContacts(request)).thenThrow(NotFoundException.class); + + String response = notificationController.getEmergencyContacts(request); + assertEquals(response, notificationController.getEmergencyContacts(request)); + } + + @Test + void testGetSupervisorEmergencyContacts() throws IEMRException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.getSupervisorEmergencyContacts(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.getSupervisorEmergencyContacts(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testGetSupervisorEmergencyContacts_Exception() throws IEMRException { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.getSupervisorEmergencyContacts(request)).thenThrow(NotFoundException.class); + + String response = notificationController.getSupervisorEmergencyContacts(request); + assertEquals(response, notificationController.getSupervisorEmergencyContacts(request)); + } + + @Test + void testCreateEmergencyContacts() throws NoSuchAlgorithmException, IOException, IEMRException, Exception { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.createEmergencyContacts(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.createEmergencyContacts(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testCreateEmergencyContacts_Exception() + throws NoSuchAlgorithmException, IOException, IEMRException, Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.createEmergencyContacts(request)).thenThrow(NotFoundException.class); + + String response = notificationController.createEmergencyContacts(request); + assertEquals(response, notificationController.createEmergencyContacts(request)); + + } + + @Test + void testUpdateEmergencyContacts() + throws NoSuchAlgorithmException, JSONException, IOException, IEMRException, Exception { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(notificationService.updateEmergencyContacts(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = notificationController.updateEmergencyContacts(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + + } + + @Test + void testUpdateEmergencyContacts_Exception() + throws NoSuchAlgorithmException, JSONException, IOException, IEMRException, Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(notificationService.updateEmergencyContacts(request)).thenThrow(NotFoundException.class); + + String response = notificationController.updateEmergencyContacts(request); + assertEquals(response, notificationController.updateEmergencyContacts(request)); + + } + +} diff --git a/src/test/java/com/iemr/common/controller/otp/OTPGatewayTest.java b/src/test/java/com/iemr/common/controller/otp/OTPGatewayTest.java new file mode 100644 index 00000000..8b546c72 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/otp/OTPGatewayTest.java @@ -0,0 +1,112 @@ +package com.iemr.common.controller.otp; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.otp.OTPRequestParsor; +import com.iemr.common.service.otp.OTPHandler; + +@ExtendWith(MockitoExtension.class) +class OTPGatewayTest { + + @Mock + private OTPHandler otpHandler; + @InjectMocks + private OTPGateway otpGatewayservice; + + @Test + void testSendOTPSuccess() throws Exception { + // Arrange + String requestJson = "{\"mobNo\":\"1234567890\"}"; + when(otpHandler.sendOTP(any(OTPRequestParsor.class))).thenReturn("success"); + + // Act + String result = otpGatewayservice.sendOTP(requestJson); + + // Assert + assertNotNull(result); + assertTrue(result.contains("success")); + } + + @Test + void testSendOTPFailure() throws Exception { + // Arrange + String requestJson = "{\"mobNo\":\"1234567890\"}"; + when(otpHandler.sendOTP(any(OTPRequestParsor.class))).thenReturn("failure"); + + // Act + String result = otpGatewayservice.sendOTP(requestJson); + + // Assert + assertNotNull(result); + assertTrue(result.contains("failure")); + } + + @Test + void testValidateOTPSuccess() throws Exception { + // Arrange + String requestJson = "{\"mobNo\":\"1234567890\",\"otp\":\"1234\"}"; + JSONObject mockResponse = new JSONObject().put("status", "success"); + when(otpHandler.validateOTP(any(OTPRequestParsor.class))).thenReturn(mockResponse); + + // Act + String result = otpGatewayservice.validateOTP(requestJson); + + // Assert + assertNotNull(result); + assertTrue(result.contains("success")); + } + + @Test + void testValidateOTPFailure() throws Exception { + // Arrange + String requestJson = "{\"mobNo\":\"1234567890\",\"otp\":\"1234\"}"; + when(otpHandler.validateOTP(any(OTPRequestParsor.class))).thenReturn(null); + + // Act + String result = otpGatewayservice.validateOTP(requestJson); + + // Assert + assertNotNull(result); + assertTrue(result.contains("failure")); + } + + @Test + void testResendOTPSuccess() throws Exception { + // Arrange + String requestJson = "{\"mobNo\":\"1234567890\"}"; + when(otpHandler.resendOTP(any(OTPRequestParsor.class))).thenReturn("success"); + + // Act + String result = otpGatewayservice.resendOTP(requestJson); + + // Assert + assertNotNull(result); + assertTrue(result.contains("success")); + } + + @Test + void testResendOTPFailure() throws Exception { + // Arrange + String requestJson = "{\"mobNo\":\"1234567890\"}"; + when(otpHandler.resendOTP(any(OTPRequestParsor.class))).thenReturn("failure"); + + // Act + String result = otpGatewayservice.resendOTP(requestJson); + + // Assert + assertNotNull(result); + assertTrue(result.contains("failure")); + } + +} diff --git a/src/test/java/com/iemr/common/controller/questionconfig/QuestionTypeControllerTest.java b/src/test/java/com/iemr/common/controller/questionconfig/QuestionTypeControllerTest.java new file mode 100644 index 00000000..6369c928 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/questionconfig/QuestionTypeControllerTest.java @@ -0,0 +1,93 @@ +package com.iemr.common.controller.questionconfig; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.service.questionconfig.QuestionTypeService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class QuestionTypeControllerTest { + + @InjectMocks + QuestionTypeController questionTypeController; + + @Mock + private QuestionTypeService questionTypeService; + + + @Test + void testCreateQuestionType() throws Exception { + String request = "{\"questionType\":\"A\", \"questionTypeDesc\":\"a\"}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(questionTypeService.createQuestionType(request)).thenReturn("any response"); // Mock the service layer to + // return whatever you deem + // as successful operation + + // Execute the test + String actualResponse = questionTypeController.createQuestionType(request); + + // Verify the interaction with the mocked service + verify(questionTypeService, times(1)).createQuestionType(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testCreateQuestionTypeException() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(questionTypeService.createQuestionType(request)).thenThrow(NotFoundException.class); + + String response = questionTypeController.createQuestionType(request); + assertEquals(response, questionTypeController.createQuestionType(request)); + } + + @Test + void testQuestionTypeList() { + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + ; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); + + when(questionTypeService.getQuestionTypeList()).thenReturn("any response"); + + String actualResponse = questionTypeController.questionTypeList(); + + // Verify the interaction with the mocked service + verify(questionTypeService, times(1)).getQuestionTypeList(); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testQuestionTypeListException() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(questionTypeService.getQuestionTypeList()).thenThrow(NotFoundException.class); + + String response = questionTypeController.questionTypeList(); + assertEquals(response, questionTypeController.questionTypeList()); + } + +} diff --git a/src/test/java/com/iemr/common/controller/questionconfig/QuestionnaireControllerTest.java b/src/test/java/com/iemr/common/controller/questionconfig/QuestionnaireControllerTest.java new file mode 100644 index 00000000..2e871272 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/questionconfig/QuestionnaireControllerTest.java @@ -0,0 +1,90 @@ +package com.iemr.common.controller.questionconfig; + +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 org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.service.questionconfig.QuestionnaireService; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class QuestionnaireControllerTest { + + @InjectMocks + QuestionnaireController questionnaireController; + + @Mock + private QuestionnaireService questionnaireService; + + @Test + void testCreateQuestionnaire() throws IEMRException { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(questionnaireService.createQuestionnaire(request)).thenReturn("any response"); + + // Execute the test + String actualResponse = questionnaireController.createQuestionnaire(request); + + // Verify the interaction with the mocked service + verify(questionnaireService, times(1)).createQuestionnaire(request); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testCreateQuestionnaireException() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(questionnaireService.createQuestionnaire(request)).thenThrow(NotFoundException.class); + + String response = questionnaireController.createQuestionnaire(request); + assertEquals(response, questionnaireController.createQuestionnaire(request)); + } + + @Test + void testQuestionTypeList() { + String request = "{}"; + String expectedResponse = "{\"data\":{\"response\":\"any response\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}"; + + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("any response"); // Set this to whatever you expect from the real operation + + when(questionnaireService.getQuestionnaireList()).thenReturn("any response"); + + // Execute the test + String actualResponse = questionnaireController.questionTypeList(); + + // Verify the interaction with the mocked service + verify(questionnaireService, times(1)).getQuestionnaireList(); + + // Assert the response + assertEquals(expectedResponse, actualResponse, "The expected and actual responses do not match"); + } + + @Test + void testQuestionTypeListException() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(questionnaireService.getQuestionnaireList()).thenThrow(NotFoundException.class); + + String response = questionnaireController.questionTypeList(); + assertEquals(response, questionnaireController.questionTypeList()); + } + +} diff --git a/src/test/java/com/iemr/common/controller/report/CustomerRelationshipReportsTest.java b/src/test/java/com/iemr/common/controller/report/CustomerRelationshipReportsTest.java new file mode 100644 index 00000000..0660ae24 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/report/CustomerRelationshipReportsTest.java @@ -0,0 +1,56 @@ +package com.iemr.common.controller.report; + +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.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.mapper.Report1097Mapper; +import com.iemr.common.service.reports.CallReportsService; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +@ExtendWith(MockitoExtension.class) +class CustomerRelationshipReportsTest { + + @InjectMocks + CustomerRelationshipReports customerRelationshipReports; + + @Mock + private CallReportsService callReportsService; + + @Mock + Report1097Mapper mapper; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + InputMapper inputMapper = new InputMapper(); + + + @Test + void testPatientAppChiefComplaintsMasterData1() throws Exception { + Integer providerServiceMapID = 1; + String expectedResponse = "expected response"; + + // String for simplicity + when(callReportsService.getReportTypes(providerServiceMapID)).thenReturn(expectedResponse); + + // The actual call to the method under test + String actualResponse = customerRelationshipReports.patientAppChiefComplaintsMasterData(providerServiceMapID); + + // Verify the interaction with the mock + verify(callReportsService).getReportTypes(providerServiceMapID); + + // Assert that the actualResponse matches what you expect + assertNotNull(actualResponse, "The response should not be null"); + assertTrue(actualResponse.contains(expectedResponse), "The response should contain the expected response"); + } +} diff --git a/src/test/java/com/iemr/common/controller/services/CategoryControllerTest.java b/src/test/java/com/iemr/common/controller/services/CategoryControllerTest.java new file mode 100644 index 00000000..03dddf66 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/services/CategoryControllerTest.java @@ -0,0 +1,67 @@ +package com.iemr.common.controller.services; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +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 java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.category.CategoryDetails; +import com.iemr.common.service.category.CategoryService; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +public class CategoryControllerTest { + + @Mock + private CategoryService categoryService; + + @InjectMocks + private CategoryController categoryController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void getAllCategoriesTest() throws Exception { + String request = "{\"providerServiceMapID\":\"1\", \"subServiceID\":\"2\", \"feedbackNatureID\":\"3\"}"; + + OutputResponse response = new OutputResponse(); + + List<CategoryDetails> mockCategoryList = new ArrayList<>(); + mockCategoryList.add(new CategoryDetails(1,"abc",true)); // Add mock details as needed + when(categoryService.getAllCategories(anyString())).thenReturn(mockCategoryList); + + + response.setResponse(mockCategoryList.toString()); + + assertEquals(response.toString(), categoryController.getAllCategries(request)); + } + + + @Test + void getAllCategories_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(categoryService.getAllCategories().toString()).thenThrow(NotFoundException.class); + + String response = categoryController.getAllCategries(request); + assertEquals(response, categoryController.getAllCategries(request)); + } +} diff --git a/src/test/java/com/iemr/common/controller/services/CommonControllerTest.java b/src/test/java/com/iemr/common/controller/services/CommonControllerTest.java new file mode 100644 index 00000000..f8854696 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/services/CommonControllerTest.java @@ -0,0 +1,178 @@ +package com.iemr.common.controller.services; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.iemr.common.service.services.CommonService; +import com.iemr.common.service.services.Services; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class CommonControllerTest { + + @InjectMocks + CommonController commonController; + + @Mock + private CommonService commonService; + + @Mock + private Services services; + + InputMapper inputMapper = new InputMapper(); + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void getCategoriesTest() throws IEMRException, JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + String request = "{\"providerServiceMapID\":1, \"subServiceID\":\"subServiceID\"}"; + OutputResponse response = new OutputResponse(); + + response.setResponse(commonService.getCategories(request).toString()); + + assertEquals(response.toString(), commonController.getCategories(request)); + } + + @Test + void getCategoriesTest_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(commonService.getCategories(request).toString()).thenThrow(NotFoundException.class); + String response = commonController.getCategories(request); + assertEquals(response, commonController.getCategories(request)); + } + + @Test + void testGetSubcategories() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"categoryID\":\"1\"}"; + OutputResponse response = new OutputResponse(); + + response.setResponse(commonService.getSubCategories(request).toString()); + + assertEquals(response.toString(), commonController.getSubcategories(request)); + + } + + @Test + void testGetSubcategories_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + when(commonService.getSubCategories(request).toString()).thenThrow(NotFoundException.class); + String response = commonController.getSubcategories(request); + assertEquals(response, commonController.getSubcategories(request)); + } + + @Test + void testGetSubCategoryFiles() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"categoryID\":\"1\", \"providerServiceMapID\":\"1\", " + "\"subCategoryID\":\"1\"}"; + OutputResponse response = new OutputResponse(); + + response.setResponse(commonService.getSubCategoryFiles(request).toString()); + + assertEquals(response.toString(), commonController.getSubCategoryFiles(request)); + } + + @Test + void testGetSubCategoryFiles_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(commonService.getSubCategoryFiles(request).toString()).thenThrow(NotFoundException.class); + + String response = commonController.getSubCategoryFiles(request); + assertEquals(response, commonController.getSubCategoryFiles(request)); + } + + @Test + void testGetSubCategoryFilesWithURL() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"categoryID\":\"1\", \"providerServiceMapID\":\"1\", " + "\"subCategoryID\":\"1\"}"; + OutputResponse response = new OutputResponse(); + + response.setResponse(commonService.getSubCategoryFilesWithURL(request).toString()); + + assertEquals(response.toString(), commonController.getSubCategoryFilesWithURL(request)); + } + + @Test + void testGetSubCategoryFilesWithURL_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(commonService.getSubCategoryFilesWithURL(request).toString()).thenThrow(NotFoundException.class); + + String response = commonController.getSubCategoryFilesWithURL(request); + assertEquals(response, commonController.getSubCategoryFilesWithURL(request)); + } + + @Test + void testGetcategoriesById() throws IEMRException, JsonMappingException, JsonProcessingException { + + String request = "{\"subServiceID\":\"1\", \"providerServiceMapID\":\"1\", " + "\"subCategoryID\":\"1\"}"; + OutputResponse response = new OutputResponse(); + + response.setResponse(commonService.getCategories(request).toString()); + + assertEquals(response.toString(), commonController.getcategoriesById(request)); + } + + @Test + void testGetcategoriesById_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(commonService.getCategories(request).toString()).thenThrow(NotFoundException.class); + + String response = commonController.getcategoriesById(request); + assertTrue(response.contains("Failed with null")); + } + + @Test + void testGetservicetypes() throws IEMRException, JsonMappingException, JsonProcessingException { + String request = "{\"\"providerServiceMapID\":\"1\"}"; + OutputResponse response = new OutputResponse(); + + response.setResponse(commonService.getActiveServiceTypes(request).toString()); + + assertEquals(response.toString(), commonController.getservicetypes(request)); + } + + @Test + void testGetservicetypes_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(commonService.getActiveServiceTypes(request).toString()).thenThrow(NotFoundException.class); + + String response = commonController.getservicetypes(request); + assertEquals(response, commonController.getservicetypes(request)); + } + + @Test + void testServiceList() { + String request = "{\"\"serviceList\":\"abc\"}"; + OutputResponse response = new OutputResponse(); + + response.setResponse(services.servicesList().toString()); + + assertEquals(response.toString(), commonController.serviceList(request)); + } + + @Test + void testServiceList_Exception() throws Exception { + String request = "{\"statusCode\":5000,\"errorMessage\":\"Failed with generic error\",\"status\":\"FAILURE\"}"; + + when(services.servicesList().toString()).thenThrow(NotFoundException.class); + + String response = commonController.serviceList(request); + assertEquals(response, commonController.serviceList(request)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/sms/SMSControllerTest.java b/src/test/java/com/iemr/common/controller/sms/SMSControllerTest.java new file mode 100644 index 00000000..e91ec1da --- /dev/null +++ b/src/test/java/com/iemr/common/controller/sms/SMSControllerTest.java @@ -0,0 +1,309 @@ +package com.iemr.common.controller.sms; + +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.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.mock.web.MockHttpServletRequest; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.iemr.common.model.sms.CreateSMSRequest; +import com.iemr.common.model.sms.SMSParameterModel; +import com.iemr.common.model.sms.SMSRequest; +import com.iemr.common.model.sms.SMSTypeModel; +import com.iemr.common.model.sms.UpdateSMSRequest; +import com.iemr.common.service.sms.SMSService; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.mapper.OutputMapper; +import com.iemr.common.utils.response.OutputResponse; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.NotFoundException; + +@ExtendWith(MockitoExtension.class) +class SMSControllerTest { + + @InjectMocks + SMSController smsController; + + @Mock + SMSService smsService; + + @Mock + private HttpServletRequest serverRequest; + + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + @Mock + InputMapper inputMapper = new InputMapper(); + private ObjectMapper objectMapper = new ObjectMapper(); + + @Test + void testGetSMSTemplates() throws Exception, JsonProcessingException { + HttpServletRequest serverRequest = mock(HttpServletRequest.class); + Map<String, Object> testResponseMap = new HashMap<>(); + testResponseMap.put("key1", "value1"); + testResponseMap.put("key2", "value2"); + String requestJson = objectMapper.createObjectNode().put("providerServiceMapID", 123).toString(); + SMSRequest request = objectMapper.readValue(requestJson, SMSRequest.class); + String testResponse = objectMapper.writeValueAsString(testResponseMap); + when(smsService.getSMSTemplates(Mockito.any())).thenReturn(testResponse); + String result = smsController.getSMSTemplates(request, serverRequest); + JsonNode resultJson = objectMapper.readTree(result); + JsonNode expData = objectMapper.readTree(testResponse); + assertEquals(expData, resultJson.get("data")); + verify(smsService, times(1)).getSMSTemplates(Mockito.any()); + } + + @Test + void getFullSMSTemplate_Success() throws Exception { + // Arrange + SMSRequest request = new SMSRequest(); // Adjust with actual parameters if needed + request.setProviderServiceMapID(1); // Example setter, adjust according to your SMSRequest class + request.setSmsTemplateID(2); // Example setter + + String expectedResponse = "Expected response"; // Adjust based on your needs + when(smsService.getFullSMSTemplate(any(SMSRequest.class))).thenReturn(expectedResponse); + + // Act + String actualResponse = smsController.getFullSMSTemplate(request, new MockHttpServletRequest()); + + // Assert + assertTrue(actualResponse.contains(expectedResponse)); + } + + @Test + void testSaveSMSTemplateSuccess() throws Exception { + // Given + CreateSMSRequest request = new CreateSMSRequest(); // Assuming you have a constructor or use a real object + when(smsService.saveSMSTemplate(any(CreateSMSRequest.class))).thenReturn("Success response"); + + // When + String result = smsController.saveSMSTemplate(request, serverRequest); + + // Then + assertNotNull(result); + // Assuming the response is a JSON or similar string. You might need to adjust + // this based on actual response structure. + assertTrue(result.contains("Success response")); + } + + @Test + void testUpdateSMSTemplateSuccess() throws Exception { + // Arrange + UpdateSMSRequest request = new UpdateSMSRequest(); // Mock or create a real instance as needed + + when(smsService.updateSMSTemplate(any(UpdateSMSRequest.class))).thenReturn("Success response"); + + // When + String result = smsController.updateSMSTemplate(request, serverRequest); + + // Then + assertNotNull(result); + // Assuming the response is a JSON or similar string. You might need to adjust + // this based on actual response structure. + assertTrue(result.contains("Success response")); + } + + @Test + void testGetSMSTypesSuccess() throws Exception { + // Arrange + SMSTypeModel request = new SMSTypeModel(); // Assume this is your request model. Initialize as needed. + + String expectedResponse = "Expected response"; + when(smsService.getSMSTypes(any(SMSTypeModel.class))).thenReturn(expectedResponse); + + // Act + String result = smsController.getSMSTypes(request, serverRequest); + + // Assert + assertNotNull(result, "Result should not be null"); + assertTrue(result.contains(expectedResponse), "Result should contain the expected response"); + } + + @Test + void testGetSMSParametersSuccess() throws Exception { + // Arrange + SMSParameterModel request = new SMSParameterModel(); // Prepare your request object + OutputResponse mockResponse = new OutputResponse(); + mockResponse.setResponse("Success response"); // Simulate a success response + + when(smsService.getSMSParameters(any(SMSParameterModel.class))).thenReturn("Success response"); + + // Act + String actualResponse = smsController.getSMSParameters(request, serverRequest); + + // Assert + assertNotNull(actualResponse); + assertTrue(actualResponse.contains("Success response")); + + verify(smsService).getSMSParameters(any(SMSParameterModel.class)); // Verify smsService was called + } + + @Test + void testSendSMSSuccess() throws Exception { + // Arrange + String jsonRequest = "[{\"providerServiceMapID\":\"1\",\"smsTemplateTypeID\":\"1\"}]"; // Simplified JSON + // input + OutputResponse expectedResponse = new OutputResponse(); + expectedResponse.setResponse("Success"); + + when(serverRequest.getHeader("Authorization")).thenReturn("Bearer token"); + when(smsService.sendSMS(anyList(), anyString())).thenReturn("Success"); + + // Act + String actualResponse = smsController.sendSMS(jsonRequest, serverRequest); + + // Assert + assertNotNull(actualResponse); + assertTrue(actualResponse.contains("Success")); + + // Verify that the service method was called with the correct parameters + verify(smsService).sendSMS(anyList(), eq("Bearer token")); + } + + @Test + void testGetFullSMSTemplateThrowsException() throws Exception { + // Setup mock for static method within the test method + try (MockedStatic<OutputMapper> mockedOutputMapper = mockStatic(OutputMapper.class)) { + Gson gson = new Gson(); // Or use your specific Gson configuration + mockedOutputMapper.when(OutputMapper::gson).thenReturn(gson); + + SMSRequest request = new SMSRequest(); + // Configure your request as needed + + MockHttpServletRequest serverRequest = new MockHttpServletRequest(); + + // Mock the service to throw an exception when called + when(smsService.getFullSMSTemplate(any(SMSRequest.class))) + .thenThrow(new RuntimeException("Test exception")); + + // Execute the method under test + String response = smsController.getFullSMSTemplate(request, serverRequest); + + // Assertions and verifications + assertNotNull(response); + assertTrue(response.contains("error")); // Adjust based on your error response format + // Verify that your service method was called as expected + verify(smsService, times(1)).getFullSMSTemplate(any(SMSRequest.class)); + } + } + + @Test + void testSaveSMSTemplateThrowsException() throws Exception { + try (MockedStatic<OutputMapper> mockedOutputMapper = Mockito.mockStatic(OutputMapper.class)) { + mockedOutputMapper.when(() -> OutputMapper.gson()).thenReturn(new Gson()); // Provide your mocked behavior + + // Setup other mocks and dependencies as necessary + SMSService smsService = mock(SMSService.class); // Mock your SMS service + + CreateSMSRequest request = new CreateSMSRequest(); // Populate your request + MockHttpServletRequest serverRequest = new MockHttpServletRequest(); // Mock request + + // Execute and assertions + String response = smsController.saveSMSTemplate(request, serverRequest); + assertNotNull(response); + assertTrue(response.contains("error")); // Adjust based on your error format + } + } + + @Test + void updateSMSTemplate_CatchBlockExecuted() throws Exception { + // Use try-with-resources to ensure MockedStatic is closed after the test + try (MockedStatic<OutputMapper> mockedOutputMapper = Mockito.mockStatic(OutputMapper.class)) { + // Mock OutputMapper.gson() to return a new Gson instance + mockedOutputMapper.when(OutputMapper::gson).thenReturn(new Gson()); + + // Mock SMSService + SMSService mockSMSService = mock(SMSService.class); + // Configure SMSService to throw an exception when updateSMSTemplate is called + + // Mock HttpServletRequest + HttpServletRequest mockRequest = mock(HttpServletRequest.class); + + // Create and populate your UpdateSMSRequest here + UpdateSMSRequest request = new UpdateSMSRequest(); + // Populate request as necessary + + // Execute the method under test + String result = smsController.updateSMSTemplate(request, mockRequest); + + // Verify the result indicates an error + assertTrue(result.contains("error"), "Expected the response to contain an error indication."); + } + } + + @Test + void getSMSTypes_CatchBlockExecuted() throws Exception { + // Mock the dependencies + SMSService mockSMSService = mock(SMSService.class); + HttpServletRequest mockRequest = mock(HttpServletRequest.class); + + // Setup MockedStatic for OutputMapper.gson() + try (MockedStatic<OutputMapper> mockedOutputMapper = Mockito.mockStatic(OutputMapper.class)) { + mockedOutputMapper.when(OutputMapper::gson).thenReturn(new Gson()); + + // Create a dummy SMSTypeModel instance as the request body + SMSTypeModel request = new SMSTypeModel(); + // Populate the request object as necessary + + // Execute the method under test + String response = smsController.getSMSTypes(request, mockRequest); + + // Verify that the response contains an error. Adjust the assertion as necessary + // based on your error handling. + assertTrue(response.contains("error"), "Expected the response to indicate an error"); + } + } + + @Test + void getSMSParameters_CatchBlockExecuted() throws Exception { + // Create mock instances for the dependencies + SMSService mockSMSService = mock(SMSService.class); + HttpServletRequest mockHttpServletRequest = mock(HttpServletRequest.class); + + // Mock static method using MockedStatic + try (MockedStatic<OutputMapper> mockedOutputMapper = Mockito.mockStatic(OutputMapper.class)) { + // Setup the mock to return a new Gson object whenever OutputMapper.gson() is + // called + mockedOutputMapper.when(OutputMapper::gson).thenReturn(new Gson()); + + // controller class name + + // Prepare your SMSParameterModel instance + SMSParameterModel request = new SMSParameterModel(); + // Set properties on the request as needed + + // Call the method under test + String result = smsController.getSMSParameters(request, mockHttpServletRequest); + + // Assert that the result contains an error message + assertTrue(result.contains("error"), + "The response should contain an error message due to the simulated exception."); + } + } + +} diff --git a/src/test/java/com/iemr/common/controller/snomedct/SnomedControllerTest.java b/src/test/java/com/iemr/common/controller/snomedct/SnomedControllerTest.java new file mode 100644 index 00000000..fb7fe306 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/snomedct/SnomedControllerTest.java @@ -0,0 +1,153 @@ +package com.iemr.common.controller.snomedct; + +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.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import com.google.gson.Gson; +import com.iemr.common.data.snomedct.SCTDescription; +import com.iemr.common.service.snomedct.SnomedService; + +class SnomedControllerTest { + + @Mock + private SnomedService snomedService; + + @InjectMocks + private SnomedController snomedController; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void getSnomedCTRecord_Success() throws Exception { + SCTDescription inputDesc = new SCTDescription(); + inputDesc.setTerm("Diabetes"); + SCTDescription outputDesc = new SCTDescription(); + outputDesc.setConceptID("123456"); + outputDesc.setTerm("Diabetes"); + + when(snomedService.findSnomedCTRecordFromTerm("Diabetes")).thenReturn(outputDesc); + + String requestJson = new Gson().toJson(inputDesc); + String response = snomedController.getSnomedCTRecord(requestJson); + + assertTrue(response.contains("123456")); + verify(snomedService, times(1)).findSnomedCTRecordFromTerm("Diabetes"); + } + + @Test + void getSnomedCTRecord_NoRecordsFound() throws Exception { + SCTDescription inputDesc = new SCTDescription(); + inputDesc.setTerm("Unknown"); + + when(snomedService.findSnomedCTRecordFromTerm("Unknown")).thenReturn(null); + + String requestJson = new Gson().toJson(inputDesc); + String response = snomedController.getSnomedCTRecord(requestJson); + + assertTrue(response.contains("No Records Found")); + verify(snomedService, times(1)).findSnomedCTRecordFromTerm("Unknown"); + } + + @Test + void getSnomedCTRecordExceptionTest() { + // Prepare test data + String requestJson = "{\"term\":\"throwException\"}"; + + // Mock behavior to throw an exception + when(snomedService.findSnomedCTRecordFromTerm(anyString())).thenThrow( RuntimeException.class); + + // Execute the test method + String actualResponse = snomedController.getSnomedCTRecord(requestJson); + + //System.out.println("actr" + actualResponse); + + // Assertions + assertNotNull(actualResponse); + // Assuming OutputResponse.toString() properly serializes error info + assertTrue(actualResponse.contains("Failed with null")); // Adjust based on your actual error handling output + + // Verify the interaction with the mocked service + verify(snomedService).findSnomedCTRecordFromTerm(anyString()); + } + + @Test + void getSnomedCTRecordListTest() throws Exception { + // Prepare test data + String requestJson = "{\"term\":\"exampleTerm\"}"; + String expectedResponse = "Mocked Response"; + SCTDescription sctDescription = new SCTDescription(); + sctDescription.setTerm("exampleTerm"); + + // Define behavior of mocks + given(snomedService.findSnomedCTRecordList(any(SCTDescription.class))).willReturn(expectedResponse); + + // Call the method to test + String actualResponse = snomedController.getSnomedCTRecordList(requestJson); + + // Verify the results + assertNotNull(actualResponse); + assertTrue(actualResponse.contains(expectedResponse)); + + // Verify interactions + verify(snomedService).findSnomedCTRecordList(any(SCTDescription.class)); + } + + @Test + void getSnomedCTRecordListNoRecordsFoundTest() throws Exception { + // Prepare test data + String requestJson = "{\"term\":\"exampleTerm\"}"; + String expectedServiceResponse = "No Records Found"; // Adjust based on actual no records message + + // Mock behavior + given(snomedService.findSnomedCTRecordList(any(SCTDescription.class))).willReturn(expectedServiceResponse); + + // Execute the test method + String actualResponse = snomedController.getSnomedCTRecordList(requestJson); + + // Assertions + assertNotNull(actualResponse); + assertTrue(actualResponse.contains("No Records Found")); + + // Verify the interaction with the mocked service + verify(snomedService).findSnomedCTRecordList(any(SCTDescription.class)); + } + + @Test + void getSnomedCTRecordListExceptionTest() throws Exception { + // Prepare test data + String requestJson = "{\"term\":\"errorTerm\"}"; + String expectedErrorMessage = "Error"; // Simplified, adjust based on your error handling + + // Mock behavior to throw an exception + willThrow(new RuntimeException("Unexpected Error")).given(snomedService) + .findSnomedCTRecordList(any(SCTDescription.class)); + + // Execute the test method + String actualResponse = snomedController.getSnomedCTRecordList(requestJson); + + // Assertions + assertNotNull(actualResponse); + assertTrue(actualResponse.contains(expectedErrorMessage)); // Verify that error message or handling is as + // expected + + // Verify the interaction with the mocked service + verify(snomedService).findSnomedCTRecordList(any(SCTDescription.class)); + } + +} diff --git a/src/test/java/com/iemr/common/controller/uptsu/UPTechnicalSupportControllerTest.java b/src/test/java/com/iemr/common/controller/uptsu/UPTechnicalSupportControllerTest.java new file mode 100644 index 00000000..65a0f57a --- /dev/null +++ b/src/test/java/com/iemr/common/controller/uptsu/UPTechnicalSupportControllerTest.java @@ -0,0 +1,106 @@ +package com.iemr.common.controller.uptsu; + +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.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.service.uptsu.UptsuService; +import com.iemr.common.utils.response.OutputResponse; + +@ExtendWith(MockitoExtension.class) +public class UPTechnicalSupportControllerTest { + + @Mock + private UptsuService uptsuService; + + @InjectMocks + private UPTechnicalSupportController controller; + + @BeforeEach + void setUp() { + // This is where you can set up common mock behaviors, if any. + } + + @Test + void testGetFacilitySuccess() { + // Arrange + Integer providerServiceMapID = 1; + String blockName = "BlockA"; + OutputResponse expectedResponse = new OutputResponse(); + expectedResponse.setResponse("Some Facility Details"); // Assume this is what getFacility would return + when(uptsuService.getFacility(providerServiceMapID, blockName)).thenReturn("Some Facility Details"); + + // Act + String actualResponse = controller.getFacility(providerServiceMapID, blockName); + + // Assert + assertNotNull(actualResponse); + // Here, you might need to parse actualResponse if it's JSON or directly compare + // if it's a simple string + assertEquals(expectedResponse.toString(), actualResponse); + verify(uptsuService, times(1)).getFacility(providerServiceMapID, blockName); + } + + @Test + void testGetFacilityException() throws Exception { + // Given + Integer providerServiceMapID = 1; + String blockName = "TestBlock"; + doThrow(RuntimeException.class).when(uptsuService).getFacility(providerServiceMapID, blockName); + + // When + String response = controller.getFacility(providerServiceMapID, blockName); + + + // Then + verify(uptsuService).getFacility(providerServiceMapID, blockName); + + assert response.contains("Failed with null"); + } + + @Test + void testSaveAppointmentDetailsSuccess() throws Exception { + String sampleRequest = "{\"key\":\"value\"}"; + String authorizationToken = "Bearer token"; + // Arrange + String expectedResponseContent = "Success"; + when(uptsuService.saveAppointmentDetails(anyString(), anyString())).thenReturn(expectedResponseContent); + + // Act + String actualResponse = controller.saveAppointmentDetails(sampleRequest, authorizationToken); + + // Assert + assertNotNull(actualResponse); + assertTrue(actualResponse.contains(expectedResponseContent)); // Simplistic check, consider using JSON parsing + // for deeper validation + verify(uptsuService, times(1)).saveAppointmentDetails(sampleRequest, authorizationToken); + } + + @Test + void testSaveAppointmentDetailsException() throws Exception { + String sampleRequest = "{\"key\":\"value\"}"; + String authorizationToken = "Bearer token"; + // Arrange + when(uptsuService.saveAppointmentDetails(anyString(), anyString())).thenThrow(RuntimeException.class); + + // Act + String actualResponse = controller.saveAppointmentDetails(sampleRequest, authorizationToken); + + // Assert + assertNotNull(actualResponse); + assertTrue(actualResponse.contains("5000")); // Assuming your error format includes the error code + } + +} diff --git a/src/test/java/com/iemr/common/controller/users/EmployeeSignatureControllerTest.java b/src/test/java/com/iemr/common/controller/users/EmployeeSignatureControllerTest.java new file mode 100644 index 00000000..525e0665 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/users/EmployeeSignatureControllerTest.java @@ -0,0 +1,155 @@ +package com.iemr.common.controller.users; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.google.common.net.HttpHeaders; +import com.iemr.common.data.users.EmployeeSignature; +import com.iemr.common.service.users.EmployeeSignatureServiceImpl; + +@ExtendWith(MockitoExtension.class) +class EmployeeSignatureControllerTest { + + private MockMvc mockMvc; + + @Mock + private EmployeeSignatureServiceImpl employeeSignatureServiceImpl; + + @InjectMocks + private EmployeeSignatureController employeeSignatureController; + + @BeforeEach + void setUp() { + mockMvc = standaloneSetup(employeeSignatureController).build(); + } + + @Test + void testFetchFile() throws Exception { + Long userId = 1L; + byte[] signature = new byte[] { 1, 2, 3 }; + EmployeeSignature employeeSignature = new EmployeeSignature(); + employeeSignature.setFileName("signature.pdf"); + employeeSignature.setFileType("application/pdf"); + employeeSignature.setSignature(signature); + + when(employeeSignatureServiceImpl.fetchSignature(userId)).thenReturn(employeeSignature); + + mockMvc.perform(get("/signature1/{userID}", userId).header("Authorization", "Bearer someToken")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.parseMediaType("application/pdf"))) + .andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"signature.pdf\"")); + + verify(employeeSignatureServiceImpl, times(1)).fetchSignature(userId); + } + + @Test + void fetchFile_ExceptionThrown_ReturnsBadRequest() throws Exception { + // Arrange + Long userID = 1L; + doThrow(RuntimeException.class).when(employeeSignatureServiceImpl).fetchSignature(anyLong()); + + // Act & Assert + MockHttpServletResponse response = mockMvc.perform( + MockMvcRequestBuilders.get("/signature1/{userID}", userID).header("Authorization", "Bearer someToken")) + .andExpect(status().isBadRequest()).andReturn().getResponse(); + + // Optionally, you can check if the response body is empty as well, as your + // method suggests it should be + assert (response.getContentLength() == 0 || new String(response.getContentAsByteArray()).isEmpty()); + } + + @Test + void testFetchFileFromCentral() throws Exception { + Long userId = 1L; + EmployeeSignature employeeSignature = new EmployeeSignature(); + employeeSignature.setUserID(1L); + // Assuming you set more fields as needed here + + when(employeeSignatureServiceImpl.fetchSignature(userId)).thenReturn(employeeSignature); + + mockMvc.perform(get("/signature1/getSignClass/{userID}", userId).header("Authorization", "Bearer someToken")) + .andExpect(status().isOk()) + // Adjust this to match expected response structure + .andExpect(content().string(containsString("\"statusCode\":200"))) + .andExpect(content().string(containsString("\"status\":\"Success\""))); + + verify(employeeSignatureServiceImpl, times(1)).fetchSignature(userId); + } + + @Test + void testFetchFileFromCentral_NoRecordFound() throws Exception { + Long userId = 1L; + when(employeeSignatureServiceImpl.fetchSignature(userId)).thenReturn(null); + + mockMvc.perform(get("/signature1/getSignClass/{userID}", userId).header("Authorization", "Bearer someToken")) + .andExpect(status().isOk()).andExpect(content().string(containsString("No record found"))); + + verify(employeeSignatureServiceImpl).fetchSignature(userId); + } + + @Test + void testFetchFileFromCentral_ExceptionThrown() throws Exception { + Long userId = 1L; + when(employeeSignatureServiceImpl.fetchSignature(userId)).thenThrow(new RuntimeException("Test exception")); + + mockMvc.perform(get("/signature1/getSignClass/{userID}", userId).header("Authorization", "Bearer someToken")) + .andExpect(status().isOk()) // Assuming your error handling still returns HTTP 200 + .andExpect(content().string(containsString("Test exception"))); + + verify(employeeSignatureServiceImpl).fetchSignature(userId); + } + + @Test + void testExistFile() throws Exception { + Long userId = 1L; + Boolean exists = true; + + when(employeeSignatureServiceImpl.existSignature(userId)).thenReturn(exists); + + mockMvc.perform(get("/signature1/signexist/{userID}", userId).header("Authorization", "Bearer someToken")) + .andExpect(status().isOk()) + // Adjust the assertion to match the JSON response structure + .andExpect(content().string(containsString("\"response\":\"true\""))) + .andExpect(content().string(containsString("\"statusCode\":200"))) + .andExpect(content().string(containsString("\"status\":\"Success\""))); + + verify(employeeSignatureServiceImpl, times(1)).existSignature(userId); + } + + @Test + void testExistFile_ExceptionThrown() throws Exception { + // Arrange + Long userId = 1L; + String expectedErrorMessage = "An error occurred"; + doThrow(new RuntimeException(expectedErrorMessage)).when(employeeSignatureServiceImpl).existSignature(userId); + + // Act & Assert + mockMvc.perform(get("/signature1/signexist/{userID}", userId).header("Authorization", "Bearer someToken")) + .andExpect(status().isOk()) // Assuming your error handling logic results in HTTP 200 + .andExpect(content().string(org.hamcrest.Matchers.containsString(expectedErrorMessage))); + + // Verify that the service method was called + verify(employeeSignatureServiceImpl).existSignature(userId); + } + +} diff --git a/src/test/java/com/iemr/common/controller/users/IEMRAdminControllerTest.java b/src/test/java/com/iemr/common/controller/users/IEMRAdminControllerTest.java new file mode 100644 index 00000000..a6084b18 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/users/IEMRAdminControllerTest.java @@ -0,0 +1,4960 @@ +package com.iemr.common.controller.users; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.common.data.callhandling.OutboundCallRequest; +import com.iemr.common.data.feedback.FeedbackDetails; +import com.iemr.common.data.institute.Designation; +import com.iemr.common.data.userbeneficiarydata.Gender; +import com.iemr.common.data.userbeneficiarydata.MaritalStatus; +import com.iemr.common.data.userbeneficiarydata.Status; +import com.iemr.common.data.userbeneficiarydata.Title; +import com.iemr.common.data.users.M_Role; +import com.iemr.common.data.users.User; +import com.iemr.common.data.users.UserLangMapping; +import com.iemr.common.data.users.UserServiceRoleMapping; +import com.iemr.common.model.user.ChangePasswordModel; +import com.iemr.common.model.user.ForceLogoutRequestModel; +import com.iemr.common.model.user.LoginRequestModel; +import com.iemr.common.notification.exception.IEMRException; +import com.iemr.common.repository.users.IEMRUserLoginSecurityRepository; +import com.iemr.common.service.users.IEMRAdminUserService; +import com.iemr.common.service.users.IEMRAdminUserServiceImpl; +import com.iemr.common.utils.encryption.AESUtil; +import com.iemr.common.utils.mapper.InputMapper; +import com.iemr.common.utils.mapper.OutputMapper; +import com.iemr.common.utils.redis.RedisSessionException; +import com.iemr.common.utils.sessionobject.SessionObject; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; + +@ExtendWith(MockitoExtension.class) +class IEMRAdminControllerTest { + @InjectMocks + private IEMRAdminController iemrAdminController; + + @Mock + private InputMapper inputMapper; + + @Mock + private IEMRAdminUserService iemrAdminUserService; + + @Test + void testLogOutUserFromConcurrentSession() { + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + + // Act and Assert + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"Invalid request object\",\"status\":\"User login failed\"}", + iemrAdminController.logOutUserFromConcurrentSession(null, new MockHttpServletRequest())); + } + + @Test + void testLogOutUserFromConcurrentSession2() { + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + + LoginRequestModel m_User = new LoginRequestModel("janedoe", "iloveyou"); + m_User.setUserName(null); + + // Act and Assert + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"Invalid request object\",\"status\":\"User login failed\"}", + iemrAdminController.logOutUserFromConcurrentSession(m_User, new MockHttpServletRequest())); + } + + @Test + void testLogOutUserFromConcurrentSession3() { + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + iemrAdminController.logOutUserFromConcurrentSession(m_User, new MockHttpServletRequest()); + + // Assert + verify(m_User, atLeast(1)).getUserName(); + } + + @Test + void testLogOutUserFromConcurrentSession4() { + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(new IEMRAdminUserServiceImpl()); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + iemrAdminController.logOutUserFromConcurrentSession(m_User, new MockHttpServletRequest()); + + // Assert + verify(m_User, atLeast(1)).getUserName(); + } + + @Test + void testLogOutUserFromConcurrentSession5() { + + // Arrange + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(new ArrayList<>()); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"User not found, please contact administrator\",\"status\":\"User login" + + " failed\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession6() { + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + + User user = new User(); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + iemrAdminController.logOutUserFromConcurrentSession(m_User, new MockHttpServletRequest()); + + // Assert + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + } + + @Test + void testLogOutUserFromConcurrentSession7() { + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + + User user = new User(); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + Designation designation2 = new Designation(); + designation2.setCreatedBy("Failed with generic error"); + designation2.setCreatedDate(mock(Timestamp.class)); + designation2.setDeleted(false); + designation2.setDesignationDesc("FAILURE"); + designation2.setDesignationID(2); + designation2.setDesignationName("FAILURE"); + designation2.setFeedbackDetails(new HashSet<>()); + designation2.setLastModDate(mock(Timestamp.class)); + designation2.setModifiedBy("Failed with generic error"); + designation2.setOutputMapper(new OutputMapper()); + designation2.setUsers(new HashSet<>()); + + Gender m_gender2 = new Gender(); + m_gender2.setCreatedBy("Failed with generic error"); + m_gender2.setCreatedDate(mock(Timestamp.class)); + m_gender2.setDeleted(false); + m_gender2.setGenderID(2); + m_gender2.setGenderName("FAILURE"); + m_gender2.setI_beneficiary(new HashSet<>()); + m_gender2.setLastModDate(mock(Timestamp.class)); + m_gender2.setM_user(new HashSet<>()); + m_gender2.setModifiedBy("Failed with generic error"); + m_gender2.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus2 = new MaritalStatus(); + m_maritalstatus2.setCreatedBy("Failed with generic error"); + m_maritalstatus2.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus2.setDeleted(false); + m_maritalstatus2.setI_beneficiary(new HashSet<>()); + m_maritalstatus2.setLastModDate(mock(Timestamp.class)); + m_maritalstatus2.setM_user(new HashSet<>()); + m_maritalstatus2.setMaritalStatusID(2); + m_maritalstatus2.setModifiedBy("Failed with generic error"); + m_maritalstatus2.setOutputMapper(new OutputMapper()); + m_maritalstatus2.setStatus("FAILURE"); + m_maritalstatus2.setStatusDesc("FAILURE"); + + Status m_status2 = new Status(); + m_status2.setCreatedBy("Failed with generic error"); + m_status2.setCreatedDate(mock(Timestamp.class)); + m_status2.setDeleted(false); + m_status2.setI_Beneficiaries(new HashSet<>()); + m_status2.setLastModDate(mock(Timestamp.class)); + m_status2.setM_Users(new HashSet<>()); + m_status2.setModifiedBy("Failed with generic error"); + m_status2.setOutputMapper(new OutputMapper()); + m_status2.setProviderServiceMappings(new HashSet<>()); + m_status2.setServiceProviders(new HashSet<>()); + m_status2.setStatus("FAILURE"); + m_status2.setStatusDesc("FAILURE"); + m_status2.setStatusID(2); + + Title m_title2 = new Title(); + m_title2.setCreatedBy("Failed with generic error"); + m_title2.setCreatedDate(mock(Timestamp.class)); + m_title2.setDeleted(false); + m_title2.setI_beneficiary(new HashSet<>()); + m_title2.setLastModDate(mock(Timestamp.class)); + m_title2.setM_user(new HashSet<>()); + m_title2.setModifiedBy("Failed with generic error"); + m_title2.setOutputMapper(new OutputMapper()); + m_title2.setTitleDesc("Mr"); + m_title2.setTitleID(2); + m_title2.setTitleName("Mr"); + + User user2 = new User(); + user2.setAadhaarNo("FAILURE"); + user2.setAgentID("FAILURE"); + user2.setAgentPassword("Failed with generic error"); + user2.setCreatedBy("Failed with generic error"); + user2.setCreatedDate(mock(Timestamp.class)); + user2.setDeleted(false); + user2.setDesignation(designation2); + user2.setDesignationID(2); + user2.setEmailID("john.smith@example.org"); + user2.setEmergencyContactNo("FAILURE"); + user2.setEmergencyContactPerson("FAILURE"); + user2.setFailedAttempt(1); + user2.setFeedbackDetails(new HashSet<>()); + user2.setFirstName("John"); + user2.setGenderID(2); + user2.setIsSupervisor(false); + user2.setLastModDate(mock(Timestamp.class)); + user2.setLastName("Smith"); + user2.setM_UserLangMappings(new HashSet<>()); + user2.setM_UserServiceRoleMapping(new ArrayList<>()); + user2.setM_gender(m_gender2); + user2.setM_maritalstatus(m_maritalstatus2); + user2.setM_status(m_status2); + user2.setM_title(m_title2); + user2.setMaritalStatusID(2); + user2.setMiddleName("FAILURE"); + user2.setModifiedBy("Failed with generic error"); + user2.setNewPassword("Failed with generic error"); + user2.setOutPutMapper(new OutputMapper()); + user2.setOutboundCallRequests(new HashSet<>()); + user2.setPassword("Failed with generic error"); + user2.setQualificationID(2); + user2.setRoleMappings(new HashSet<>()); + user2.setStatusID(2); + user2.setTitleID(2); + user2.setUserID(2L); + user2.setUserName("Failed with generic error"); + user2.setdOB(mock(Timestamp.class)); + user2.setdOJ(mock(Timestamp.class)); + user2.setpAN("FAILURE"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user2); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"More than 1 user found, please contact administrator\",\"status\":\"User" + + " login failed\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession8() { + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(new SessionObject()); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + iemrAdminController.logOutUserFromConcurrentSession(m_User, new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + } + + @Test + void testLogOutUserFromConcurrentSession9() throws RedisSessionException { + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("Session Object"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("Session Object")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession10() throws RedisSessionException { + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("Failed with generic error"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("Failed with generic error")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession11() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("FAILURE"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("FAILURE")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession12() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("{\"response\":\"$$STRING\"}"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("{\"response\":\"$$STRING\"}")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession13() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("$$STRING"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("$$STRING")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession14() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("foo"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("foo")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession15() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn(null); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).getSessionObject(("janedoe")); + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"Unable to fetch session from redis\",\"status\":\"User login failed\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession16() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("42"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("42")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession17() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn("janedoe"); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + SessionObject sessionObject = mock(SessionObject.class); + doNothing().when(sessionObject).deleteSessionObject(Mockito.<String>any()); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn(""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + String actualLogOutUserFromConcurrentSessionResult = iemrAdminController.logOutUserFromConcurrentSession(m_User, + new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(sessionObject).deleteSessionObject(("")); + verify(sessionObject, atLeast(1)).getSessionObject(Mockito.<String>any()); + assertEquals( + "{\"data\":{\"response\":\"User successfully logged out\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status" + + "\":\"Success\"}", + actualLogOutUserFromConcurrentSessionResult); + } + + @Test + void testLogOutUserFromConcurrentSession18() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + User user = mock(User.class); + when(user.getUserName()).thenReturn(null); + doNothing().when(user).setAadhaarNo(Mockito.<String>any()); + doNothing().when(user).setAgentID(Mockito.<String>any()); + doNothing().when(user).setAgentPassword(Mockito.<String>any()); + doNothing().when(user).setCreatedBy(Mockito.<String>any()); + doNothing().when(user).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(user).setDeleted(Mockito.<Boolean>any()); + doNothing().when(user).setDesignation(Mockito.<Designation>any()); + doNothing().when(user).setDesignationID(Mockito.<Integer>any()); + doNothing().when(user).setEmailID(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactNo(Mockito.<String>any()); + doNothing().when(user).setEmergencyContactPerson(Mockito.<String>any()); + doNothing().when(user).setFailedAttempt(Mockito.<Integer>any()); + doNothing().when(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + doNothing().when(user).setFirstName(Mockito.<String>any()); + doNothing().when(user).setGenderID(Mockito.<Integer>any()); + doNothing().when(user).setIsSupervisor(Mockito.<Boolean>any()); + doNothing().when(user).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(user).setLastName(Mockito.<String>any()); + doNothing().when(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + doNothing().when(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + doNothing().when(user).setM_gender(Mockito.<Gender>any()); + doNothing().when(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + doNothing().when(user).setM_status(Mockito.<Status>any()); + doNothing().when(user).setM_title(Mockito.<Title>any()); + doNothing().when(user).setMaritalStatusID(Mockito.<Integer>any()); + doNothing().when(user).setMiddleName(Mockito.<String>any()); + doNothing().when(user).setModifiedBy(Mockito.<String>any()); + doNothing().when(user).setNewPassword(Mockito.<String>any()); + doNothing().when(user).setOutPutMapper(Mockito.<OutputMapper>any()); + doNothing().when(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + doNothing().when(user).setPassword(Mockito.<String>any()); + doNothing().when(user).setQualificationID(Mockito.<Integer>any()); + doNothing().when(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + doNothing().when(user).setStatusID(Mockito.<Integer>any()); + doNothing().when(user).setTitleID(Mockito.<Integer>any()); + doNothing().when(user).setUserID(Mockito.<Long>any()); + doNothing().when(user).setUserName(Mockito.<String>any()); + doNothing().when(user).setdOB(Mockito.<Timestamp>any()); + doNothing().when(user).setdOJ(Mockito.<Timestamp>any()); + doNothing().when(user).setpAN(Mockito.<String>any()); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(mock(SessionObject.class)); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + LoginRequestModel m_User = mock(LoginRequestModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + + // Act + iemrAdminController.logOutUserFromConcurrentSession(m_User, new MockHttpServletRequest()); + + // Assert + verify(user).getUserName(); + verify(user).setAadhaarNo(("Failed with generic error")); + verify(user).setAgentID(("Failed with generic error")); + verify(user).setAgentPassword(("iloveyou")); + verify(user).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(user).setCreatedDate(Mockito.<Timestamp>any()); + verify(user).setDeleted(Mockito.<Boolean>any()); + verify(user).setDesignation(Mockito.<Designation>any()); + verify(user).setDesignationID(Mockito.<Integer>any()); + verify(user).setEmailID(("jane.doe@example.org")); + verify(user).setEmergencyContactNo(("Failed with generic error")); + verify(user).setEmergencyContactPerson(("Failed with generic error")); + verify(user).setFailedAttempt(Mockito.<Integer>any()); + verify(user).setFeedbackDetails(Mockito.<Set<FeedbackDetails>>any()); + verify(user).setFirstName(("Jane")); + verify(user).setGenderID(Mockito.<Integer>any()); + verify(user).setIsSupervisor(Mockito.<Boolean>any()); + verify(user).setLastModDate(Mockito.<Timestamp>any()); + verify(user).setLastName(("Doe")); + verify(user).setM_UserLangMappings(Mockito.<Set<UserLangMapping>>any()); + verify(user).setM_UserServiceRoleMapping(Mockito.<List<UserServiceRoleMapping>>any()); + verify(user).setM_gender(Mockito.<Gender>any()); + verify(user).setM_maritalstatus(Mockito.<MaritalStatus>any()); + verify(user).setM_status(Mockito.<Status>any()); + verify(user).setM_title(Mockito.<Title>any()); + verify(user).setMaritalStatusID(Mockito.<Integer>any()); + verify(user).setMiddleName(("Failed with generic error")); + verify(user).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(user).setNewPassword(("iloveyou")); + verify(user).setOutPutMapper(Mockito.<OutputMapper>any()); + verify(user).setOutboundCallRequests(Mockito.<Set<OutboundCallRequest>>any()); + verify(user).setPassword(("iloveyou")); + verify(user).setQualificationID(Mockito.<Integer>any()); + verify(user).setRoleMappings(Mockito.<Set<UserServiceRoleMapping>>any()); + verify(user).setStatusID(Mockito.<Integer>any()); + verify(user).setTitleID(Mockito.<Integer>any()); + verify(user).setUserID(Mockito.<Long>any()); + verify(user).setUserName(("janedoe")); + verify(user).setdOB(Mockito.<Timestamp>any()); + verify(user).setdOJ(Mockito.<Timestamp>any()); + verify(user).setpAN(("Failed with generic error")); + verify(m_User, atLeast(1)).getUserName(); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + } + +// +// @Test +// void testSuperUserAuthenticate() { +// fail("Not yet implemented"); +// } +// +// @Test +// void testGetLoginResponse() { +// fail("Not yet implemented"); +// } + + @Test + void testGetLoginResponse() throws RedisSessionException { + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("Session Object"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"Session Object\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse2() throws RedisSessionException { + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("Failed with generic error"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"Failed with generic error\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse3() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("FAILURE"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"FAILURE\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse4() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("{\"response\":\"$$STRING\"}"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse5() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("$$STRING"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse6() throws RedisSessionException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("foo"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"foo\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse7() throws RedisSessionException { + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn("42"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"42\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse8() throws RedisSessionException { + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())).thenReturn(""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + String actualLoginResponse = iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + assertEquals( + "{\"data\":{\"response\":\"\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLoginResponse); + } + + @Test + void testGetLoginResponse9() throws RedisSessionException { + + // Arrange + SessionObject sessionObject = mock(SessionObject.class); + when(sessionObject.getSessionObject(Mockito.<String>any())) + .thenThrow(new RedisSessionException("An error occurred")); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setSessionObject(sessionObject); + HttpServletRequestWrapper request = mock(HttpServletRequestWrapper.class); + when(request.getHeader(Mockito.<String>any())).thenReturn("https://example.org/example"); + + // Act + iemrAdminController.getLoginResponse(request); + + // Assert + verify(sessionObject).getSessionObject(("https://example.org/example")); + verify(request).getHeader(("Authorization")); + } + +// +// @Test +// void testForgetPassword() { +// fail("Not yet implemented"); +// } +// + + @Test + void testForgetPassword() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + ChangePasswordModel m_User = mock(ChangePasswordModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + doNothing().when(m_User).setIsAdmin(Mockito.<Boolean>any()); + doNothing().when(m_User).setNewPassword(Mockito.<String>any()); + doNothing().when(m_User).setPassword(Mockito.<String>any()); + doNothing().when(m_User).setTransactionId(Mockito.<String>any()); + doNothing().when(m_User).setUserName(Mockito.<String>any()); + m_User.setIsAdmin(true); + m_User.setNewPassword("iloveyou"); + m_User.setPassword("iloveyou"); + m_User.setTransactionId("42"); + m_User.setUserName("janedoe"); + + // Act + iemrAdminController.forgetPassword(m_User); + + // Assert + verify(m_User).getUserName(); + verify(m_User).setIsAdmin(Mockito.<Boolean>any()); + verify(m_User).setNewPassword(("iloveyou")); + verify(m_User).setPassword(("iloveyou")); + verify(m_User).setTransactionId(("42")); + verify(m_User).setUserName(("janedoe")); + } + + /** + * Method under test: + * {@link IEMRAdminController#forgetPassword(ChangePasswordModel)} + */ + @Test + void testForgetPassword2() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(new IEMRAdminUserServiceImpl()); + ChangePasswordModel m_User = mock(ChangePasswordModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + doNothing().when(m_User).setIsAdmin(Mockito.<Boolean>any()); + doNothing().when(m_User).setNewPassword(Mockito.<String>any()); + doNothing().when(m_User).setPassword(Mockito.<String>any()); + doNothing().when(m_User).setTransactionId(Mockito.<String>any()); + doNothing().when(m_User).setUserName(Mockito.<String>any()); + m_User.setIsAdmin(true); + m_User.setNewPassword("iloveyou"); + m_User.setPassword("iloveyou"); + m_User.setTransactionId("42"); + m_User.setUserName("janedoe"); + + // Act + iemrAdminController.forgetPassword(m_User); + + // Assert + verify(m_User).getUserName(); + verify(m_User).setIsAdmin(Mockito.<Boolean>any()); + verify(m_User).setNewPassword(("iloveyou")); + verify(m_User).setPassword(("iloveyou")); + verify(m_User).setTransactionId(("42")); + verify(m_User).setUserName(("janedoe")); + } + + /** + * Method under test: + * {@link IEMRAdminController#forgetPassword(ChangePasswordModel)} + */ + @Test + void testForgetPassword3() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(new ArrayList<>()); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + ChangePasswordModel m_User = mock(ChangePasswordModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + doNothing().when(m_User).setIsAdmin(Mockito.<Boolean>any()); + doNothing().when(m_User).setNewPassword(Mockito.<String>any()); + doNothing().when(m_User).setPassword(Mockito.<String>any()); + doNothing().when(m_User).setTransactionId(Mockito.<String>any()); + doNothing().when(m_User).setUserName(Mockito.<String>any()); + m_User.setIsAdmin(true); + m_User.setNewPassword("iloveyou"); + m_User.setPassword("iloveyou"); + m_User.setTransactionId("42"); + m_User.setUserName("janedoe"); + + // Act + String actualForgetPasswordResult = iemrAdminController.forgetPassword(m_User); + + // Assert + verify(m_User).getUserName(); + verify(m_User).setIsAdmin(Mockito.<Boolean>any()); + verify(m_User).setNewPassword(("iloveyou")); + verify(m_User).setPassword(("iloveyou")); + verify(m_User).setTransactionId(("42")); + verify(m_User).setUserName(("janedoe")); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"user not found, please contact administrator\",\"status\":\"User login" + + " failed\"}", + actualForgetPasswordResult); + } + + /** + * Method under test: + * {@link IEMRAdminController#forgetPassword(ChangePasswordModel)} + */ + @Test + void testForgetPassword4() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + + User user = new User(); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userSecurityQuestion(Mockito.<Long>any())).thenReturn(new ArrayList<>()); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + ChangePasswordModel m_User = mock(ChangePasswordModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + doNothing().when(m_User).setIsAdmin(Mockito.<Boolean>any()); + doNothing().when(m_User).setNewPassword(Mockito.<String>any()); + doNothing().when(m_User).setPassword(Mockito.<String>any()); + doNothing().when(m_User).setTransactionId(Mockito.<String>any()); + doNothing().when(m_User).setUserName(Mockito.<String>any()); + m_User.setIsAdmin(true); + m_User.setNewPassword("iloveyou"); + m_User.setPassword("iloveyou"); + m_User.setTransactionId("42"); + m_User.setUserName("janedoe"); + + // Act + String actualForgetPasswordResult = iemrAdminController.forgetPassword(m_User); + + // Assert + verify(m_User).getUserName(); + verify(m_User).setIsAdmin(Mockito.<Boolean>any()); + verify(m_User).setNewPassword(("iloveyou")); + verify(m_User).setPassword(("iloveyou")); + verify(m_User).setTransactionId(("42")); + verify(m_User).setUserName(("janedoe")); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + verify(iemrAdminUserService).userSecurityQuestion(Mockito.<Long>any()); + assertEquals( + "{\"data\":{\"SecurityQuesAns\":[]},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualForgetPasswordResult); + } + + @Test + void testForgetPassword7() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + Designation designation = new Designation(); + designation.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + designation.setCreatedDate(mock(Timestamp.class)); + designation.setDeleted(true); + designation.setDesignationDesc("Failed with generic error"); + designation.setDesignationID(1); + designation.setDesignationName("Failed with generic error"); + designation.setFeedbackDetails(new HashSet<>()); + designation.setLastModDate(mock(Timestamp.class)); + designation.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + designation.setOutputMapper(new OutputMapper()); + designation.setUsers(new HashSet<>()); + + Gender m_gender = new Gender(); + m_gender.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_gender.setCreatedDate(mock(Timestamp.class)); + m_gender.setDeleted(true); + m_gender.setGenderID(1); + m_gender.setGenderName("Failed with generic error"); + m_gender.setI_beneficiary(new HashSet<>()); + m_gender.setLastModDate(mock(Timestamp.class)); + m_gender.setM_user(new HashSet<>()); + m_gender.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_gender.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus = new MaritalStatus(); + m_maritalstatus.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_maritalstatus.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus.setDeleted(true); + m_maritalstatus.setI_beneficiary(new HashSet<>()); + m_maritalstatus.setLastModDate(mock(Timestamp.class)); + m_maritalstatus.setM_user(new HashSet<>()); + m_maritalstatus.setMaritalStatusID(1); + m_maritalstatus.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_maritalstatus.setOutputMapper(new OutputMapper()); + m_maritalstatus.setStatus("Failed with generic error"); + m_maritalstatus.setStatusDesc("Failed with generic error"); + + Status m_status = new Status(); + m_status.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_status.setCreatedDate(mock(Timestamp.class)); + m_status.setDeleted(true); + m_status.setI_Beneficiaries(new HashSet<>()); + m_status.setLastModDate(mock(Timestamp.class)); + m_status.setM_Users(new HashSet<>()); + m_status.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_status.setOutputMapper(new OutputMapper()); + m_status.setProviderServiceMappings(new HashSet<>()); + m_status.setServiceProviders(new HashSet<>()); + m_status.setStatus("Failed with generic error"); + m_status.setStatusDesc("Failed with generic error"); + m_status.setStatusID(1); + + Title m_title = new Title(); + m_title.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_title.setCreatedDate(mock(Timestamp.class)); + m_title.setDeleted(true); + m_title.setI_beneficiary(new HashSet<>()); + m_title.setLastModDate(mock(Timestamp.class)); + m_title.setM_user(new HashSet<>()); + m_title.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_title.setOutputMapper(new OutputMapper()); + m_title.setTitleDesc("Dr"); + m_title.setTitleID(1); + m_title.setTitleName("Dr"); + + User user = new User(); + user.setAadhaarNo("Failed with generic error"); + user.setAgentID("Failed with generic error"); + user.setAgentPassword("iloveyou"); + user.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + user.setCreatedDate(mock(Timestamp.class)); + user.setDeleted(true); + user.setDesignation(designation); + user.setDesignationID(1); + user.setEmailID("jane.doe@example.org"); + user.setEmergencyContactNo("Failed with generic error"); + user.setEmergencyContactPerson("Failed with generic error"); + user.setFailedAttempt(5000); + user.setFeedbackDetails(new HashSet<>()); + user.setFirstName("Jane"); + user.setGenderID(1); + user.setIsSupervisor(true); + user.setLastModDate(mock(Timestamp.class)); + user.setLastName("Doe"); + user.setM_UserLangMappings(new HashSet<>()); + user.setM_UserServiceRoleMapping(new ArrayList<>()); + user.setM_gender(m_gender); + user.setM_maritalstatus(m_maritalstatus); + user.setM_status(m_status); + user.setM_title(m_title); + user.setMaritalStatusID(1); + user.setMiddleName("Failed with generic error"); + user.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + user.setNewPassword("iloveyou"); + user.setOutPutMapper(new OutputMapper()); + user.setOutboundCallRequests(new HashSet<>()); + user.setPassword("iloveyou"); + user.setQualificationID(1); + user.setRoleMappings(new HashSet<>()); + user.setStatusID(1); + user.setTitleID(1); + user.setUserID(1L); + user.setUserName("janedoe"); + user.setdOB(mock(Timestamp.class)); + user.setdOJ(mock(Timestamp.class)); + user.setpAN("Failed with generic error"); + + Designation designation2 = new Designation(); + designation2.setCreatedBy("Failed with generic error"); + designation2.setCreatedDate(mock(Timestamp.class)); + designation2.setDeleted(false); + designation2.setDesignationDesc("FAILURE"); + designation2.setDesignationID(2); + designation2.setDesignationName("FAILURE"); + designation2.setFeedbackDetails(new HashSet<>()); + designation2.setLastModDate(mock(Timestamp.class)); + designation2.setModifiedBy("Failed with generic error"); + designation2.setOutputMapper(new OutputMapper()); + designation2.setUsers(new HashSet<>()); + + Gender m_gender2 = new Gender(); + m_gender2.setCreatedBy("Failed with generic error"); + m_gender2.setCreatedDate(mock(Timestamp.class)); + m_gender2.setDeleted(false); + m_gender2.setGenderID(2); + m_gender2.setGenderName("FAILURE"); + m_gender2.setI_beneficiary(new HashSet<>()); + m_gender2.setLastModDate(mock(Timestamp.class)); + m_gender2.setM_user(new HashSet<>()); + m_gender2.setModifiedBy("Failed with generic error"); + m_gender2.setOutputMapper(new OutputMapper()); + + MaritalStatus m_maritalstatus2 = new MaritalStatus(); + m_maritalstatus2.setCreatedBy("Failed with generic error"); + m_maritalstatus2.setCreatedDate(mock(Timestamp.class)); + m_maritalstatus2.setDeleted(false); + m_maritalstatus2.setI_beneficiary(new HashSet<>()); + m_maritalstatus2.setLastModDate(mock(Timestamp.class)); + m_maritalstatus2.setM_user(new HashSet<>()); + m_maritalstatus2.setMaritalStatusID(2); + m_maritalstatus2.setModifiedBy("Failed with generic error"); + m_maritalstatus2.setOutputMapper(new OutputMapper()); + m_maritalstatus2.setStatus("FAILURE"); + m_maritalstatus2.setStatusDesc("FAILURE"); + + Status m_status2 = new Status(); + m_status2.setCreatedBy("Failed with generic error"); + m_status2.setCreatedDate(mock(Timestamp.class)); + m_status2.setDeleted(false); + m_status2.setI_Beneficiaries(new HashSet<>()); + m_status2.setLastModDate(mock(Timestamp.class)); + m_status2.setM_Users(new HashSet<>()); + m_status2.setModifiedBy("Failed with generic error"); + m_status2.setOutputMapper(new OutputMapper()); + m_status2.setProviderServiceMappings(new HashSet<>()); + m_status2.setServiceProviders(new HashSet<>()); + m_status2.setStatus("FAILURE"); + m_status2.setStatusDesc("FAILURE"); + m_status2.setStatusID(2); + + Title m_title2 = new Title(); + m_title2.setCreatedBy("Failed with generic error"); + m_title2.setCreatedDate(mock(Timestamp.class)); + m_title2.setDeleted(false); + m_title2.setI_beneficiary(new HashSet<>()); + m_title2.setLastModDate(mock(Timestamp.class)); + m_title2.setM_user(new HashSet<>()); + m_title2.setModifiedBy("Failed with generic error"); + m_title2.setOutputMapper(new OutputMapper()); + m_title2.setTitleDesc("Mr"); + m_title2.setTitleID(2); + m_title2.setTitleName("Mr"); + + User user2 = new User(); + user2.setAadhaarNo("FAILURE"); + user2.setAgentID("FAILURE"); + user2.setAgentPassword("Failed with generic error"); + user2.setCreatedBy("Failed with generic error"); + user2.setCreatedDate(mock(Timestamp.class)); + user2.setDeleted(false); + user2.setDesignation(designation2); + user2.setDesignationID(2); + user2.setEmailID("john.smith@example.org"); + user2.setEmergencyContactNo("FAILURE"); + user2.setEmergencyContactPerson("FAILURE"); + user2.setFailedAttempt(1); + user2.setFeedbackDetails(new HashSet<>()); + user2.setFirstName("John"); + user2.setGenderID(2); + user2.setIsSupervisor(false); + user2.setLastModDate(mock(Timestamp.class)); + user2.setLastName("Smith"); + user2.setM_UserLangMappings(new HashSet<>()); + user2.setM_UserServiceRoleMapping(new ArrayList<>()); + user2.setM_gender(m_gender2); + user2.setM_maritalstatus(m_maritalstatus2); + user2.setM_status(m_status2); + user2.setM_title(m_title2); + user2.setMaritalStatusID(2); + user2.setMiddleName("FAILURE"); + user2.setModifiedBy("Failed with generic error"); + user2.setNewPassword("Failed with generic error"); + user2.setOutPutMapper(new OutputMapper()); + user2.setOutboundCallRequests(new HashSet<>()); + user2.setPassword("Failed with generic error"); + user2.setQualificationID(2); + user2.setRoleMappings(new HashSet<>()); + user2.setStatusID(2); + user2.setTitleID(2); + user2.setUserID(2L); + user2.setUserName("Failed with generic error"); + user2.setdOB(mock(Timestamp.class)); + user2.setdOJ(mock(Timestamp.class)); + user2.setpAN("FAILURE"); + + ArrayList<User> userList = new ArrayList<>(); + userList.add(user2); + userList.add(user); + IEMRAdminUserService iemrAdminUserService = mock(IEMRAdminUserService.class); + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(userList); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + ChangePasswordModel m_User = mock(ChangePasswordModel.class); + when(m_User.getUserName()).thenReturn("janedoe"); + doNothing().when(m_User).setIsAdmin(Mockito.<Boolean>any()); + doNothing().when(m_User).setNewPassword(Mockito.<String>any()); + doNothing().when(m_User).setPassword(Mockito.<String>any()); + doNothing().when(m_User).setTransactionId(Mockito.<String>any()); + doNothing().when(m_User).setUserName(Mockito.<String>any()); + m_User.setIsAdmin(true); + m_User.setNewPassword("iloveyou"); + m_User.setPassword("iloveyou"); + m_User.setTransactionId("42"); + m_User.setUserName("janedoe"); + + // Act + String actualForgetPasswordResult = iemrAdminController.forgetPassword(m_User); + + // Assert + verify(m_User).getUserName(); + verify(m_User).setIsAdmin(Mockito.<Boolean>any()); + verify(m_User).setNewPassword(("iloveyou")); + verify(m_User).setPassword(("iloveyou")); + verify(m_User).setTransactionId(("42")); + verify(m_User).setUserName(("janedoe")); + verify(iemrAdminUserService).userExitsCheck(("janedoe")); + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"more than 1 user found, please contact administrator\",\"status\":\"User" + + " login failed\"}", + actualForgetPasswordResult); + } + + @Test + void testChangePassword() throws Exception { + // Arrange + when(iemrAdminUserService.userExitsCheck(Mockito.<String>any())).thenReturn(new ArrayList<>()); + + ChangePasswordModel changePasswordModel = new ChangePasswordModel(); + changePasswordModel.setIsAdmin(true); + changePasswordModel.setNewPassword("iloveyou"); + changePasswordModel.setPassword("iloveyou"); + changePasswordModel.setTransactionId("42"); + changePasswordModel.setUserName("janedoe"); + + changePasswordModel.toString(); + + String content = (new ObjectMapper()).writeValueAsString(changePasswordModel); + MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/user/changePassword") + .contentType(MediaType.APPLICATION_JSON).content(content); + + // Act and Assert + MockMvcBuilders.standaloneSetup(iemrAdminController).build().perform(requestBuilder) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().contentType("application/json")) + .andExpect(MockMvcResultMatchers.content().string( + "{\"statusCode\":5002,\"errorMessage\":\"Change password failed with error as user is not available\",\"status\":\"User" + + " login failed\"}")); + } + + void testSaveUserSecurityQuesAns() { + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(new IEMRAdminUserServiceImpl()); + + // Act and Assert + assertEquals( + "{\"statusCode\":5002,\"errorMessage\":\"Invalid user, please contact administrator\",\"status\":\"User login" + + " failed\"}", + iemrAdminController.saveUserSecurityQuesAns(new ArrayList<>())); + } + + @Test + void testGetSecurityts() { + + // Arrange + IEMRUserLoginSecurityRepository iEMRUserLoginSecurityRepository = mock(IEMRUserLoginSecurityRepository.class); + when(iEMRUserLoginSecurityRepository.getAllLoginSecurityQuestions()).thenReturn(new ArrayList<>()); + + IEMRAdminUserServiceImpl iemrAdminUserService = new IEMRAdminUserServiceImpl(); + iemrAdminUserService.setIEMRUserLoginSecurityRepository(iEMRUserLoginSecurityRepository); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualSecurityts = iemrAdminController.getSecurityts(); + + // Assert + verify(iEMRUserLoginSecurityRepository).getAllLoginSecurityQuestions(); + assertEquals("{\"data\":[],\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualSecurityts); + } + + @Test + void testGetSecurityts2() { + + // Arrange + ArrayList<Object[]> objectArrayList = new ArrayList<>(); + objectArrayList.add(new Object[] { "42" }); + IEMRUserLoginSecurityRepository iEMRUserLoginSecurityRepository = mock(IEMRUserLoginSecurityRepository.class); + when(iEMRUserLoginSecurityRepository.getAllLoginSecurityQuestions()).thenReturn(objectArrayList); + + IEMRAdminUserServiceImpl iemrAdminUserService = new IEMRAdminUserServiceImpl(); + iemrAdminUserService.setIEMRUserLoginSecurityRepository(iEMRUserLoginSecurityRepository); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + iemrAdminController.getSecurityts(); + + // Assert + verify(iEMRUserLoginSecurityRepository).getAllLoginSecurityQuestions(); + } + + @Test + void testGetRolesByProviderID() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException, JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("Roles By Provider ID"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Roles By Provider ID\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID2() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("Failed with generic error"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Failed with generic error\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID3() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("FAILURE"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"FAILURE\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID4() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())) + .thenReturn("{\"response\":\"$$STRING\"}"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID5() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("$$STRING"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID6() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("foo"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"foo\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID7() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn(""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID8() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("42"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"42\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetRolesByProviderID9() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("\""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + } + + @Test + void testGetRolesByProviderID10() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getRolesByProviderID(Mockito.<String>any())).thenReturn("'"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualRolesByProviderID = iemrAdminController.getRolesByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getRolesByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\\u0027\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualRolesByProviderID); + } + + @Test + void testGetUsersByProviderID() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("Users By Provider ID"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Users By Provider ID\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID2() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("Failed with generic error"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Failed with generic error\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID3() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("FAILURE"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"FAILURE\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID4() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())) + .thenReturn("{\"response\":\"$$STRING\"}"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID5() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("$$STRING"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID6() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("foo"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"foo\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID7() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn(""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID8() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("42"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"42\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUsersByProviderID9() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("\""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + } + + @Test + void testGetUsersByProviderID10() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getUsersByProviderID(Mockito.<String>any())).thenReturn("'"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualUsersByProviderID = iemrAdminController.getUsersByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getUsersByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\\u0027\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualUsersByProviderID); + } + + @Test + void testGetUserServicePointVanDetails() { + // Arrange, Act and Assert + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getUserServicePointVanDetails("Coming Request")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getUserServicePointVanDetails("")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getUserServicePointVanDetails("foo")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getUserServicePointVanDetails("42")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()) + .getUserServicePointVanDetails("com.iemr.common.data.users.UserSecurityQMapping")); + } + + @Test + void testGetUserServicePointVanDetails2() { + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setAesUtil(mock(AESUtil.class)); + + // Act and Assert + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + iemrAdminController.getUserServicePointVanDetails("Coming Request")); + } + + @Test + void testGetServicepointVillages() { + + // Arrange, Act and Assert + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getServicepointVillages("Coming Request")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getServicepointVillages("")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getServicepointVillages("foo")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getServicepointVillages("42")); + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + (new IEMRAdminController()).getServicepointVillages("com.iemr.common.data.users.UserSecurityQMapping")); + } + + @Test + void testGetServicepointVillages2() { + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setAesUtil(mock(AESUtil.class)); + + // Act and Assert + assertEquals( + "{\"statusCode\":5001,\"errorMessage\":\"Invalid object conversion\",\"status\":\"Invalid object conversion\"}", + iemrAdminController.getServicepointVillages("Coming Request")); + } + + @Test + void testGetLocationsByProviderID() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())) + .thenReturn("Locations By Provider ID"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Locations By Provider ID\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID2() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())) + .thenReturn("Failed with generic error"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Failed with generic error\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID3() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())).thenReturn("FAILURE"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"FAILURE\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID4() throws Exception { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())) + .thenReturn("{\"response\":\"$$STRING\"}"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID5() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())).thenReturn("$$STRING"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID6() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())).thenReturn("foo"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"foo\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID7() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())).thenReturn(""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID8() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())).thenReturn("42"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"42\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID9() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())).thenReturn("\""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + } + + @Test + void testGetLocationsByProviderID10() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())).thenReturn("'"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\\u0027\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualLocationsByProviderID); + } + + @Test + void testGetLocationsByProviderID11() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getLocationsByProviderID(Mockito.<String>any())) + .thenThrow(new IEMRException("An error occurred")); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualLocationsByProviderID = iemrAdminController.getLocationsByProviderID("Request"); + + // Assert + verify(iemrAdminUserService).getLocationsByProviderID(("Request")); + assertEquals("{\"statusCode\":5002,\"errorMessage\":\"An error occurred\",\"status\":\"User login failed\"}", + actualLocationsByProviderID); + } + + @Test + void testForceLogout() { + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + ForceLogoutRequestModel request = mock(ForceLogoutRequestModel.class); + doNothing().when(request).setPassword(Mockito.<String>any()); + doNothing().when(request).setProviderServiceMapID(Mockito.<Integer>any()); + doNothing().when(request).setUserName(Mockito.<String>any()); + request.setPassword("iloveyou"); + request.setProviderServiceMapID(1); + request.setUserName("janedoe"); + + // Act + iemrAdminController.forceLogout(request); + + // Assert + verify(request).setPassword(("iloveyou")); + verify(request).setProviderServiceMapID(Mockito.<Integer>any()); + verify(request).setUserName(("janedoe")); + } + + @Test + void testForceLogout2() { + + // Arrange + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(new IEMRAdminUserServiceImpl()); + ForceLogoutRequestModel request = mock(ForceLogoutRequestModel.class); + when(request.getUserName()).thenReturn("janedoe"); + doNothing().when(request).setPassword(Mockito.<String>any()); + doNothing().when(request).setProviderServiceMapID(Mockito.<Integer>any()); + doNothing().when(request).setUserName(Mockito.<String>any()); + request.setPassword("iloveyou"); + request.setProviderServiceMapID(1); + request.setUserName("janedoe"); + + // Act + iemrAdminController.forceLogout(request); + + // Assert + verify(request).getUserName(); + verify(request).setPassword(("iloveyou")); + verify(request).setProviderServiceMapID(Mockito.<Integer>any()); + verify(request).setUserName(("janedoe")); + } + + @Test + void testForceLogout3() throws Exception { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + doNothing().when(iemrAdminUserService).forceLogout(Mockito.<ForceLogoutRequestModel>any()); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + ForceLogoutRequestModel request = mock(ForceLogoutRequestModel.class); + doNothing().when(request).setPassword(Mockito.<String>any()); + doNothing().when(request).setProviderServiceMapID(Mockito.<Integer>any()); + doNothing().when(request).setUserName(Mockito.<String>any()); + request.setPassword("iloveyou"); + request.setProviderServiceMapID(1); + request.setUserName("janedoe"); + + // Act + String actualForceLogoutResult = iemrAdminController.forceLogout(request); + + // Assert + verify(request).setPassword(("iloveyou")); + verify(request).setProviderServiceMapID(Mockito.<Integer>any()); + verify(request).setUserName(("janedoe")); + verify(iemrAdminUserService).forceLogout(Mockito.<ForceLogoutRequestModel>any()); + assertEquals( + "{\"data\":{\"response\":\"Success\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualForceLogoutResult); + } + + @Test + void testForceLogout4() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + doThrow(new Exception("Failed with generic error")).when(iemrAdminUserService) + .forceLogout(Mockito.<ForceLogoutRequestModel>any()); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + ForceLogoutRequestModel request = mock(ForceLogoutRequestModel.class); + doNothing().when(request).setPassword(Mockito.<String>any()); + doNothing().when(request).setProviderServiceMapID(Mockito.<Integer>any()); + doNothing().when(request).setUserName(Mockito.<String>any()); + request.setPassword("iloveyou"); + request.setProviderServiceMapID(1); + request.setUserName("janedoe"); + + // Act + iemrAdminController.forceLogout(request); + + // Assert + verify(request).setPassword(("iloveyou")); + verify(request).setProviderServiceMapID(Mockito.<Integer>any()); + verify(request).setUserName(("janedoe")); + verify(iemrAdminUserService).forceLogout(Mockito.<ForceLogoutRequestModel>any()); + } + + @Test + void testForceLogout5() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + doThrow(new Exception("")).when(iemrAdminUserService).forceLogout(Mockito.<ForceLogoutRequestModel>any()); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + ForceLogoutRequestModel request = mock(ForceLogoutRequestModel.class); + doNothing().when(request).setPassword(Mockito.<String>any()); + doNothing().when(request).setProviderServiceMapID(Mockito.<Integer>any()); + doNothing().when(request).setUserName(Mockito.<String>any()); + request.setPassword("iloveyou"); + request.setProviderServiceMapID(1); + request.setUserName("janedoe"); + + // Act + iemrAdminController.forceLogout(request); + + // Assert + verify(request).setPassword(("iloveyou")); + verify(request).setProviderServiceMapID(Mockito.<Integer>any()); + verify(request).setUserName(("janedoe")); + verify(iemrAdminUserService).forceLogout(Mockito.<ForceLogoutRequestModel>any()); + } + + @Test + void testForceLogout6() throws Exception { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + doThrow(new IEMRException("An error occurred")).when(iemrAdminUserService) + .forceLogout(Mockito.<ForceLogoutRequestModel>any()); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + ForceLogoutRequestModel request = mock(ForceLogoutRequestModel.class); + doNothing().when(request).setPassword(Mockito.<String>any()); + doNothing().when(request).setProviderServiceMapID(Mockito.<Integer>any()); + doNothing().when(request).setUserName(Mockito.<String>any()); + request.setPassword("iloveyou"); + request.setProviderServiceMapID(1); + request.setUserName("janedoe"); + + // Act + String actualForceLogoutResult = iemrAdminController.forceLogout(request); + + // Assert + verify(request).setPassword(("iloveyou")); + verify(request).setProviderServiceMapID(Mockito.<Integer>any()); + verify(request).setUserName(("janedoe")); + verify(iemrAdminUserService).forceLogout(Mockito.<ForceLogoutRequestModel>any()); + assertEquals("{\"statusCode\":5002,\"errorMessage\":\"An error occurred\",\"status\":\"User login failed\"}", + actualForceLogoutResult); + } + + @Test + void testGetAgentByRoleID() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("Agent By Role ID"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Agent By Role ID\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID2() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("Failed with generic error"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"Failed with generic error\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":" + + "\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID3() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("FAILURE"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"FAILURE\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID4() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("{\"response\":\"$$STRING\"}"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID5() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("$$STRING"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"$$STRING\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID6() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("foo"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"foo\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID7() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn(""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID8() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("42"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"42\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID9() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("\""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + } + + @Test + void testGetAgentByRoleID10() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn("'"); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Request"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Request")); + assertEquals( + "{\"data\":{\"response\":\"\\u0027\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetAgentByRoleID12() throws IEMRException, com.iemr.common.utils.exception.IEMRException, + JsonMappingException, JsonProcessingException { + + // Arrange + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getAgentByRoleID(Mockito.<String>any())).thenReturn(""); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + String actualAgentByRoleID = iemrAdminController.getAgentByRoleID("Failed with generic error"); + + // Assert + verify(iemrAdminUserService).getAgentByRoleID(("Failed with generic error")); + assertEquals( + "{\"data\":{\"response\":\"\"},\"statusCode\":200,\"errorMessage\":\"Success\",\"status\":\"Success\"}", + actualAgentByRoleID); + } + + @Test + void testGetrolewrapuptime2() { + + // Arrange + M_Role m_Role = mock(M_Role.class); + doNothing().when(m_Role).setCreatedBy(Mockito.<String>any()); + doNothing().when(m_Role).setCreatedDate(Mockito.<Timestamp>any()); + doNothing().when(m_Role).setDeleted(anyBoolean()); + doNothing().when(m_Role).setIsWrapUpTime(Mockito.<Boolean>any()); + doNothing().when(m_Role).setLastModDate(Mockito.<Timestamp>any()); + doNothing().when(m_Role).setModifiedBy(Mockito.<String>any()); + doNothing().when(m_Role).setRoleDesc(Mockito.<String>any()); + doNothing().when(m_Role).setRoleID(anyInt()); + doNothing().when(m_Role).setRoleName(Mockito.<String>any()); + doNothing().when(m_Role).setWrapUpTime(Mockito.<Integer>any()); + m_Role.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + m_Role.setCreatedDate(mock(Timestamp.class)); + m_Role.setDeleted(true); + m_Role.setIsWrapUpTime(true); + m_Role.setLastModDate(mock(Timestamp.class)); + m_Role.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + m_Role.setRoleDesc("Role Desc"); + m_Role.setRoleID(1); + m_Role.setRoleName("Role Name"); + m_Role.setWrapUpTime(1); + IEMRAdminUserServiceImpl iemrAdminUserService = mock(IEMRAdminUserServiceImpl.class); + when(iemrAdminUserService.getrolewrapuptime(Mockito.<Integer>any())).thenReturn(m_Role); + + IEMRAdminController iemrAdminController = new IEMRAdminController(); + iemrAdminController.setIemrAdminUserService(iemrAdminUserService); + + // Act + iemrAdminController.getrolewrapuptime(1); + + // Assert + verify(m_Role).setCreatedBy(("Jan 1, 2020 8:00am GMT+0100")); + verify(m_Role).setCreatedDate(Mockito.<Timestamp>any()); + verify(m_Role).setDeleted((true)); + verify(m_Role).setIsWrapUpTime(Mockito.<Boolean>any()); + verify(m_Role).setLastModDate(Mockito.<Timestamp>any()); + verify(m_Role).setModifiedBy(("Jan 1, 2020 9:00am GMT+0100")); + verify(m_Role).setRoleDesc(("Role Desc")); + verify(m_Role).setRoleID((1)); + verify(m_Role).setRoleName(("Role Name")); + verify(m_Role).setWrapUpTime(Mockito.<Integer>any()); + verify(iemrAdminUserService).getrolewrapuptime(Mockito.<Integer>any()); + } + +} diff --git a/src/test/java/com/iemr/common/controller/version/VersionControllerTest.java b/src/test/java/com/iemr/common/controller/version/VersionControllerTest.java new file mode 100644 index 00000000..38571499 --- /dev/null +++ b/src/test/java/com/iemr/common/controller/version/VersionControllerTest.java @@ -0,0 +1,94 @@ +package com.iemr.common.controller.version; + +// +//import org.junit.jupiter.api.Test; +//import org.junit.jupiter.api.extension.ExtendWith; +//import org.mockito.InjectMocks; +//import org.mockito.Mock; +//import org.mockito.junit.jupiter.MockitoExtension; +//import org.springframework.test.util.ReflectionTestUtils; +// +//import java.io.BufferedReader; +//import java.io.ByteArrayInputStream; +//import java.io.IOException; +//import java.io.InputStream; +//import java.io.InputStreamReader; +//import java.lang.reflect.Method; +// +//import static org.junit.jupiter.api.Assertions.assertEquals; +//import static org.junit.jupiter.api.Assertions.assertNotNull; +// +//@ExtendWith(MockitoExtension.class) +//class VersionControllerTest { +// private static final String EXPECTED_RESPONSE = "version=1.0\n"; +// +// @InjectMocks +// private VersionController versionController; +// +// @Test +// void testVersionInformation() throws Exception { +// String inputData = "version=1.0"; +// InputStream inputStream = new ByteArrayInputStream(inputData.getBytes()); +// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); +// +// Method readFromInputStreamMethod = VersionController.class.getDeclaredMethod("readFromInputStream", +// InputStream.class); +// readFromInputStreamMethod.setAccessible(true); +// +// // Act +// String actualResponse = (String) readFromInputStreamMethod.invoke(versionController, inputStream); +// +// // Assert +// assertNotNull(actualResponse); +// assertEquals(EXPECTED_RESPONSE, actualResponse); +// } +//} +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class VersionControllerTest { + private static final String EXPECTED_RESPONSE = "version=1.0\n"; + + @InjectMocks + private VersionController versionController; + private MockMvc mockMvc; + + @Test + void testReadFromInputStream() throws Exception { + String inputData = "version=1.0"; + InputStream inputStream = new ByteArrayInputStream(inputData.getBytes()); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + + Method readFromInputStreamMethod = VersionController.class.getDeclaredMethod("readFromInputStream", + InputStream.class); + readFromInputStreamMethod.setAccessible(true); + + // Act + String actualResponse = (String) readFromInputStreamMethod.invoke(versionController, inputStream); + + // Assert + assertNotNull(actualResponse); + assertEquals(EXPECTED_RESPONSE, actualResponse); + } +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/BenRelationshipTypeServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/BenRelationshipTypeServiceImplTest.java new file mode 100644 index 00000000..2fd07e1b --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/BenRelationshipTypeServiceImplTest.java @@ -0,0 +1,93 @@ +package com.iemr.common.service.beneficiary; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.beneficiary.BenRelationshipType; +import com.iemr.common.repository.beneficiary.BeneficiaryRelationshipTypeRepository; + +@ExtendWith(MockitoExtension.class) +class BenRelationshipTypeServiceImplTest { + @InjectMocks + private BenRelationshipTypeServiceImpl benRelationshipTypeServiceImpl; + + @Mock + private BeneficiaryRelationshipTypeRepository beneficiaryRelationshipTypeRepository; + + + + @Test + void testGetActiveRelationshipTypes() { + when(beneficiaryRelationshipTypeRepository.getActiveRelationships()).thenReturn(new HashSet<>()); + + List<BenRelationshipType> actualActiveRelationshipTypes = benRelationshipTypeServiceImpl + .getActiveRelationshipTypes(); + + verify(beneficiaryRelationshipTypeRepository).getActiveRelationships(); + assertTrue(actualActiveRelationshipTypes.isEmpty()); + } + + @Test + void testGetActiveRelationshipTypes2() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[]{"42"}); + when(beneficiaryRelationshipTypeRepository.getActiveRelationships()).thenReturn(objectArraySet); + + List<BenRelationshipType> actualActiveRelationshipTypes = benRelationshipTypeServiceImpl + .getActiveRelationshipTypes(); + + verify(beneficiaryRelationshipTypeRepository).getActiveRelationships(); + assertTrue(actualActiveRelationshipTypes.isEmpty()); + } + + @Test + void testGetActiveRelationshipTypes3() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(null); + when(beneficiaryRelationshipTypeRepository.getActiveRelationships()).thenReturn(objectArraySet); + + List<BenRelationshipType> actualActiveRelationshipTypes = benRelationshipTypeServiceImpl + .getActiveRelationshipTypes(); + + verify(beneficiaryRelationshipTypeRepository).getActiveRelationships(); + assertTrue(actualActiveRelationshipTypes.isEmpty()); + } + + @Test + void testGetActiveRelationshipTypes4() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[]{2, "42"}); + when(beneficiaryRelationshipTypeRepository.getActiveRelationships()).thenReturn(objectArraySet); + + List<BenRelationshipType> actualActiveRelationshipTypes = benRelationshipTypeServiceImpl + .getActiveRelationshipTypes(); + + verify(beneficiaryRelationshipTypeRepository).getActiveRelationships(); + assertEquals(1, actualActiveRelationshipTypes.size()); + } + + @Test + void testGetActiveRelationshipTypes5() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[]{1, "42"}); + when(beneficiaryRelationshipTypeRepository.getActiveRelationships()).thenReturn(objectArraySet); + + List<BenRelationshipType> actualActiveRelationshipTypes = benRelationshipTypeServiceImpl + .getActiveRelationshipTypes(); + + verify(beneficiaryRelationshipTypeRepository).getActiveRelationships(); + assertEquals(1, actualActiveRelationshipTypes.size()); + } +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/BeneficiaryOccupationServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/BeneficiaryOccupationServiceImplTest.java new file mode 100644 index 00000000..2f3d23f1 --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/BeneficiaryOccupationServiceImplTest.java @@ -0,0 +1,93 @@ +package com.iemr.common.service.beneficiary; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; + +import com.iemr.common.data.beneficiary.BeneficiaryOccupation; +import com.iemr.common.repository.beneficiary.BeneficiaryOccupationRepository; + +@ExtendWith(MockitoExtension.class) +class BeneficiaryOccupationServiceImplTest { + @Mock + private BeneficiaryOccupationRepository beneficiaryOccupationRepository; + + @InjectMocks + private BeneficiaryOccupationServiceImpl beneficiaryOccupationServiceImpl; + + + + + @Test + void testGetActiveOccupations() { + // Arrange + when(beneficiaryOccupationRepository.getActiveOccupations()).thenReturn(new HashSet<>()); + + // Act + List<BeneficiaryOccupation> actualActiveOccupations = beneficiaryOccupationServiceImpl.getActiveOccupations(); + + // Assert + verify(beneficiaryOccupationRepository).getActiveOccupations(); + assertTrue(actualActiveOccupations.isEmpty()); + } + + + @Test + void testGetActiveOccupations2() { + // Arrange + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[]{"42"}); + when(beneficiaryOccupationRepository.getActiveOccupations()).thenReturn(objectArraySet); + + // Act + List<BeneficiaryOccupation> actualActiveOccupations = beneficiaryOccupationServiceImpl.getActiveOccupations(); + + // Assert + verify(beneficiaryOccupationRepository).getActiveOccupations(); + assertTrue(actualActiveOccupations.isEmpty()); + } + + + @Test + void testGetActiveOccupations3() { + // Arrange + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(null); + when(beneficiaryOccupationRepository.getActiveOccupations()).thenReturn(objectArraySet); + + // Act + List<BeneficiaryOccupation> actualActiveOccupations = beneficiaryOccupationServiceImpl.getActiveOccupations(); + + // Assert + verify(beneficiaryOccupationRepository).getActiveOccupations(); + assertTrue(actualActiveOccupations.isEmpty()); + } + + + @Test + void testGetActiveOccupations4() { + // Arrange + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[]{1L, "42"}); + when(beneficiaryOccupationRepository.getActiveOccupations()).thenReturn(objectArraySet); + + // Act + List<BeneficiaryOccupation> actualActiveOccupations = beneficiaryOccupationServiceImpl.getActiveOccupations(); + + // Assert + verify(beneficiaryOccupationRepository).getActiveOccupations(); + assertEquals(1, actualActiveOccupations.size()); + } +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/GovtIdentityTypeServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/GovtIdentityTypeServiceImplTest.java new file mode 100644 index 00000000..dc0009fc --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/GovtIdentityTypeServiceImplTest.java @@ -0,0 +1,64 @@ +package com.iemr.common.service.beneficiary; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.util.HashSet; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.beneficiary.GovtIdentityType; +import com.iemr.common.repository.beneficiary.GovtIdentityTypeRepository; + +@ExtendWith(MockitoExtension.class) +class GovtIdentityTypeServiceImplTest { + @Mock + private GovtIdentityTypeRepository govtIdentityTypeRepository; + + @InjectMocks + private GovtIdentityTypeServiceImpl govtIdentityTypeServiceImpl; + + + @Test + void testGetActiveIDTypes() { + Object[] data1 = new Object[] { 1, "Passport", true }; + Object[] data2 = new Object[] { 2, "Driver's License", true }; + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(data1); + objectArraySet.add(data2); + + when(govtIdentityTypeRepository.getActiveIDTypes()).thenReturn(objectArraySet); + List<GovtIdentityType> actualActiveIDTypes = govtIdentityTypeServiceImpl.getActiveIDTypes(); + verify(govtIdentityTypeRepository).getActiveIDTypes(); + assertEquals(2, actualActiveIDTypes.size()); + } + + @Test + void testGetActiveIDTypes2() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + when(govtIdentityTypeRepository.getActiveIDTypes()).thenReturn(objectArraySet); + List<GovtIdentityType> actualActiveIDTypes = govtIdentityTypeServiceImpl.getActiveIDTypes(); + verify(govtIdentityTypeRepository).getActiveIDTypes(); + assertTrue(actualActiveIDTypes.isEmpty()); + } + + @Test + void testGetActiveIDTypes3() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(null); + when(govtIdentityTypeRepository.getActiveIDTypes()).thenReturn(objectArraySet); + List<GovtIdentityType> actualActiveIDTypes = govtIdentityTypeServiceImpl.getActiveIDTypes(); + verify(govtIdentityTypeRepository).getActiveIDTypes(); + assertTrue(actualActiveIDTypes.isEmpty()); + } +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/IEMRBeneficiaryTypeServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/IEMRBeneficiaryTypeServiceImplTest.java new file mode 100644 index 00000000..11ce413e --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/IEMRBeneficiaryTypeServiceImplTest.java @@ -0,0 +1,73 @@ +package com.iemr.common.service.beneficiary; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; + +import com.iemr.common.data.beneficiary.BeneficiaryType; +import com.iemr.common.repository.beneficiary.IEMRBeneficiaryTypeRepository; +import com.iemr.common.utils.mapper.OutputMapper; + +@ExtendWith(MockitoExtension.class) +class IEMRBeneficiaryTypeServiceImplTest { + @Mock + private IEMRBeneficiaryTypeRepository iEMRBeneficiaryTypeRepository; + + @InjectMocks + private IEMRBeneficiaryTypeServiceImpl iEMRBeneficiaryTypeServiceImpl; + + @Test + void testAddRelation() { + BeneficiaryType beneficiaryType = new BeneficiaryType(); + beneficiaryType.setBeneficiaryType("Beneficiary Type"); + beneficiaryType.setBeneficiaryTypeID((short) 1); + beneficiaryType.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + beneficiaryType.setCreatedDate(mock(Timestamp.class)); + beneficiaryType.setDeleted(true); + beneficiaryType.setLastModDate(mock(Timestamp.class)); + beneficiaryType.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + beneficiaryType.setOutputMapper(new OutputMapper()); + when(iEMRBeneficiaryTypeRepository.save(Mockito.<BeneficiaryType>any())).thenReturn(beneficiaryType); + + BeneficiaryType i_beneficiaryType = new BeneficiaryType(); + i_beneficiaryType.setBeneficiaryType("Beneficiary Type"); + i_beneficiaryType.setBeneficiaryTypeID((short) 1); + i_beneficiaryType.setCreatedBy("Jan 1, 2020 8:00am GMT+0100"); + i_beneficiaryType.setCreatedDate(mock(Timestamp.class)); + i_beneficiaryType.setDeleted(true); + i_beneficiaryType.setLastModDate(mock(Timestamp.class)); + i_beneficiaryType.setModifiedBy("Jan 1, 2020 9:00am GMT+0100"); + i_beneficiaryType.setOutputMapper(new OutputMapper()); + + BeneficiaryType actualAddRelationResult = iEMRBeneficiaryTypeServiceImpl.addRelation(i_beneficiaryType); + + verify(iEMRBeneficiaryTypeRepository).save(Mockito.<BeneficiaryType>any()); + assertSame(beneficiaryType, actualAddRelationResult); + } + + @Test + void testGetRelations() { + ArrayList<BeneficiaryType> beneficiaryTypeList = new ArrayList<>(); + when(iEMRBeneficiaryTypeRepository.findAll()).thenReturn(beneficiaryTypeList); + + Iterable<BeneficiaryType> actualRelations = iEMRBeneficiaryTypeServiceImpl.getRelations(); + + verify(iEMRBeneficiaryTypeRepository).findAll(); + assertTrue(((List<BeneficiaryType>) actualRelations).isEmpty()); + assertSame(beneficiaryTypeList, actualRelations); + } +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/IEMRSearchUserServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/IEMRSearchUserServiceImplTest.java new file mode 100644 index 00000000..03ee159a --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/IEMRSearchUserServiceImplTest.java @@ -0,0 +1,335 @@ +package com.iemr.common.service.beneficiary; + +import static org.hamcrest.CoreMatchers.any; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +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 java.math.BigInteger; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.iemr.common.data.beneficiary.BenPhoneMap; +import com.iemr.common.data.everwell.BenPhoneMaps; +import com.iemr.common.dto.identity.Address; +import com.iemr.common.dto.identity.BenDetailDTO; +import com.iemr.common.dto.identity.BeneficiariesDTO; +import com.iemr.common.dto.identity.IdentitySearchDTO; +import com.iemr.common.mapper.BenCompleteDetailMapper; +import com.iemr.common.mapper.BenPhoneMapperDecorator; +import com.iemr.common.mapper.CommunityMapper; +import com.iemr.common.mapper.DistrictBlockMapper; +import com.iemr.common.mapper.DistrictBranchMapper; +import com.iemr.common.mapper.DistrictMapper; +import com.iemr.common.mapper.EducationMapper; +import com.iemr.common.mapper.GenderMapper; +import com.iemr.common.mapper.GovtIdentityTypeMapper; +import com.iemr.common.mapper.HealthCareWorkerMapper; +import com.iemr.common.mapper.IdentityBenEditMapper; +import com.iemr.common.mapper.MaritalStatusMapper; +import com.iemr.common.mapper.RelationshipMapper; +import com.iemr.common.mapper.SexualOrientationMapper; +import com.iemr.common.mapper.StateMapper; +import com.iemr.common.mapper.TitleMapper; +import com.iemr.common.model.beneficiary.BenPhoneMapModel; +import com.iemr.common.model.beneficiary.BeneficiaryDemographicsModel; +import com.iemr.common.model.beneficiary.BeneficiaryModel; +import com.iemr.common.repository.beneficiary.BeneficiaryRelationshipTypeRepository; +import com.iemr.common.repository.beneficiary.CommunityRepository; +import com.iemr.common.repository.beneficiary.EducationRepository; +import com.iemr.common.repository.beneficiary.GovtIdentityTypeRepository; +import com.iemr.common.repository.location.LocationDistrictBlockRepository; +import com.iemr.common.repository.location.LocationDistrictRepository; +import com.iemr.common.repository.location.LocationDistrilctBranchRepository; +import com.iemr.common.repository.location.LocationStateRepository; +import com.iemr.common.repository.userbeneficiarydata.GenderRepository; +import com.iemr.common.repository.userbeneficiarydata.MaritalStatusRepository; +import com.iemr.common.repository.userbeneficiarydata.SexualOrientationRepository; +import com.iemr.common.repository.userbeneficiarydata.TitleRepository; +import com.iemr.common.utils.mapper.OutputMapper; + +@ExtendWith(MockitoExtension.class) +class IEMRSearchUserServiceImplTest { + @Mock + private BenCompleteDetailMapper benCompleteDetailMapper; + + @Mock + private BenPhoneMapperDecorator benPhoneMapperDecorator; + + @Mock + private BeneficiaryRelationshipTypeRepository beneficiaryRelationshipTypeRepository; + + @Mock + private CommunityMapper communityMapper; + + @Mock + private CommunityRepository communityRepository; + + @Mock + private DistrictBlockMapper districtBlockMapper; + + @Mock + private DistrictBranchMapper districtBranchMapper; + + @Mock + private DistrictMapper districtMapper; + + @Mock + private EducationMapper educationMapper; + + @Mock + private EducationRepository educationRepository; + + @Mock + private GenderMapper genderMapper; + + @Mock + private GenderRepository genderRepository; + + @Mock + private GovtIdentityTypeMapper govtIdentityTypeMapper; + + @Mock + private GovtIdentityTypeRepository govtIdentityTypeRepository; + + @Mock + private HealthCareWorkerMapper healthCareWorkerMapper; + + @InjectMocks + private IEMRSearchUserServiceImpl iEMRSearchUserServiceImpl; + + @Mock + private IdentityBenEditMapper identityBenEditMapper; + + @Mock + private IdentityBeneficiaryService identityBeneficiaryService; + + @Mock + private LocationDistrictBlockRepository locationDistrictBlockRepository; + + @Mock + private LocationDistrictRepository locationDistrictRepository; + + @Mock + private LocationDistrilctBranchRepository locationDistrilctBranchRepository; + + @Mock + private LocationStateRepository locationStateRepository; + + @Mock + private MaritalStatusMapper maritalStatusMapper; + + @Mock + private MaritalStatusRepository maritalStatusRepository; + + @Mock + private RelationshipMapper relationshipMapper; + + @Mock + private SexualOrientationMapper sexualOrientationMapper; + + @Mock + private SexualOrientationRepository sexualOrientationRepository; + + @Mock + private StateMapper stateMapper; + + @Mock + private TitleMapper titleMapper; + + @Mock + private TitleRepository titleRepository; + @Mock + BenPhoneMapperDecorator benPhoneMapper; + @Mock + private BenCompleteDetailMapper benCompleteMapper; + @Mock + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void testUserExitsCheckWithId() throws Exception { + // Arrange + when(identityBeneficiaryService.getBeneficiaryListByBenRegID(Mockito.<Long>any(), Mockito.<String>any(), + Mockito.<Boolean>any())).thenReturn(new ArrayList<>()); + + // Act + List<BeneficiaryModel> actualUserExitsCheckWithIdResult = iEMRSearchUserServiceImpl.userExitsCheckWithId(1L, + "Auth", true); + + // Assert + verify(identityBeneficiaryService).getBeneficiaryListByBenRegID(Mockito.<Long>any(), eq("Auth"), + Mockito.<Boolean>any()); + assertTrue(actualUserExitsCheckWithIdResult.isEmpty()); + } + + @Test + void testUserExitsCheckWithId2() throws Exception { + // Arrange + when(identityBeneficiaryService.getBeneficiaryListByBenID(Mockito.<String>any(), Mockito.<String>any(), + Mockito.<Boolean>any())).thenReturn(new ArrayList<>()); + + // Act + List<BeneficiaryModel> actualUserExitsCheckWithIdResult = iEMRSearchUserServiceImpl + .userExitsCheckWithId("Beneficiary ID", "Auth", true); + + // Assert + verify(identityBeneficiaryService).getBeneficiaryListByBenID(eq("Beneficiary ID"), eq("Auth"), + Mockito.<Boolean>any()); + assertTrue(actualUserExitsCheckWithIdResult.isEmpty()); + } + + @Test + void testUserExitsCheckWithHealthId_ABHAId() throws Exception { + // Arrange + when(identityBeneficiaryService.getBeneficiaryListByHealthID_ABHAAddress(Mockito.<String>any(), + Mockito.<String>any(), Mockito.<Boolean>any())).thenReturn(new ArrayList<>()); + + // Act + List<BeneficiaryModel> actualUserExitsCheckWithHealthId_ABHAIdResult = iEMRSearchUserServiceImpl + .userExitsCheckWithHealthId_ABHAId("Health ID", "Auth", true); + + // Assert + verify(identityBeneficiaryService).getBeneficiaryListByHealthID_ABHAAddress(eq("Health ID"), eq("Auth"), + Mockito.<Boolean>any()); + assertTrue(actualUserExitsCheckWithHealthId_ABHAIdResult.isEmpty()); + } + + @Test + void testUserExitsCheckWithHealthIdNo_ABHAIdNo() throws Exception { + // Arrange + when(identityBeneficiaryService.getBeneficiaryListByHealthIDNo_ABHAIDNo(Mockito.<String>any(), + Mockito.<String>any(), Mockito.<Boolean>any())).thenReturn(new ArrayList<>()); + + // Act + List<BeneficiaryModel> actualUserExitsCheckWithHealthIdNo_ABHAIdNoResult = iEMRSearchUserServiceImpl + .userExitsCheckWithHealthIdNo_ABHAIdNo("Health IDNo", "Auth", true); + + // Assert + verify(identityBeneficiaryService).getBeneficiaryListByHealthIDNo_ABHAIDNo(eq("Health IDNo"), eq("Auth"), + Mockito.<Boolean>any()); + assertTrue(actualUserExitsCheckWithHealthIdNo_ABHAIdNoResult.isEmpty()); + } + + @Test + void testUserExitsCheckWithFamilyId() throws Exception { + // Arrange + when(identityBeneficiaryService.getBeneficiaryListByFamilyId(Mockito.<String>any(), Mockito.<String>any(), + Mockito.<Boolean>any())).thenReturn(new ArrayList<>()); + + // Act + List<BeneficiaryModel> actualUserExitsCheckWithFamilyIdResult = iEMRSearchUserServiceImpl + .userExitsCheckWithFamilyId("42", "Auth", true); + + // Assert + verify(identityBeneficiaryService).getBeneficiaryListByFamilyId(eq("42"), eq("Auth"), Mockito.<Boolean>any()); + assertTrue(actualUserExitsCheckWithFamilyIdResult.isEmpty()); + } + + @Test + void testUserExitsCheckWithGovIdentity() throws Exception { + // Arrange + when(identityBeneficiaryService.getBeneficiaryListByGovId(Mockito.<String>any(), Mockito.<String>any(), + Mockito.<Boolean>any())).thenReturn(new ArrayList<>()); + + // Act + List<BeneficiaryModel> actualUserExitsCheckWithGovIdentityResult = iEMRSearchUserServiceImpl + .userExitsCheckWithGovIdentity("Identity", "Auth", true); + + // Assert + verify(identityBeneficiaryService).getBeneficiaryListByGovId(eq("Identity"), eq("Auth"), + Mockito.<Boolean>any()); + assertTrue(actualUserExitsCheckWithGovIdentityResult.isEmpty()); + } + + @Test + void testFindByBeneficiaryPhoneNo() throws Exception { + // Arrange + when(identityBeneficiaryService.getBeneficiaryListByPhone(Mockito.<String>any(), Mockito.<String>any(), + Mockito.<Boolean>any())).thenReturn(new ArrayList<>()); + + // Act + String actualFindByBeneficiaryPhoneNoResult = iEMRSearchUserServiceImpl + .findByBeneficiaryPhoneNo(new BenPhoneMap(), 1, 1, "Auth"); + + // Assert + verify(identityBeneficiaryService).getBeneficiaryListByPhone(isNull(), eq("Auth"), Mockito.<Boolean>any()); + assertEquals("[]", actualFindByBeneficiaryPhoneNoResult); + } + + @Test + void testGetBeneficiaryListFromMapper() { + // Arrange, Act and Assert + assertTrue(iEMRSearchUserServiceImpl.getBeneficiaryListFromMapper(new ArrayList<>()).isEmpty()); + } + + @Test + void testGetBeneficiaryListFromMapper_NonEmptyList() { + BeneficiariesDTO beneficiaryDTO = mock(BeneficiariesDTO.class); + + List<BeneficiariesDTO> beneficiariesDTOList = Collections.singletonList(beneficiaryDTO); + + BeneficiaryModel beneficiaryModel = new BeneficiaryModel(); + when(benCompleteMapper.benDetailForOutboundDTOToIBeneficiary(beneficiaryDTO)).thenReturn(beneficiaryModel); + + when(benPhoneMapper.benPhoneMapToResponseByID(Mockito.any())).thenReturn(null); + + when(sexualOrientationMapper.sexualOrientationByIDToModel((Short) null)).thenReturn(null); + + when(govtIdentityTypeMapper.govtIdentityTypeModelByIDToModel(Mockito.any())).thenReturn(null); + + when(benCompleteMapper.createBenDemographicsModel(Mockito.any())) + .thenReturn(mock(BeneficiaryDemographicsModel.class)); + + when(healthCareWorkerMapper.getModelByWorkerID(Mockito.anyShort())).thenReturn(null); + + when(genderMapper.genderByIDToLoginResponse(Mockito.any())).thenReturn(null); + + when(maritalStatusMapper.maritalStatusByIDToResponse(Mockito.any())).thenReturn(null); + + when(titleMapper.titleByIDToResponse(Mockito.anyInt())).thenReturn(null); + + when(beneficiaryDTO.getAbhaDetails()).thenReturn(null); + + BenDetailDTO beneficiaryDetails = mock(BenDetailDTO.class); + when(beneficiaryDTO.getBeneficiaryDetails()).thenReturn(beneficiaryDetails); + + // Test + + List<BeneficiaryModel> result = iEMRSearchUserServiceImpl.getBeneficiaryListFromMapper(beneficiariesDTOList); + + // Verify + + assertFalse(result.isEmpty()); + + assertEquals(1, result.size()); + + assertEquals(beneficiaryModel, result.get(0)); + + } + +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/IdentityBeneficiaryServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/IdentityBeneficiaryServiceImplTest.java new file mode 100644 index 00000000..3ff51c6a --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/IdentityBeneficiaryServiceImplTest.java @@ -0,0 +1,66 @@ +package com.iemr.common.service.beneficiary; + +import org.junit.jupiter.api.Timeout; +import org.mockito.InjectMocks; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import org.mockito.MockitoAnnotations; + +import java.util.Set; + +import com.iemr.common.repository.beneficiary.GovtIdentityTypeRepository; +import com.iemr.common.data.beneficiary.GovtIdentityType; + +import java.util.HashSet; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.verify; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.mockito.Mockito.mock; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.mockito.Mockito.doReturn; +import static org.hamcrest.Matchers.is; + +@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) +class IdentityBeneficiaryServiceImplTest { + + private final GovtIdentityTypeRepository govtIdentityTypeRepositoryMock = mock(GovtIdentityTypeRepository.class, "govtIdentityTypeRepository"); + + private AutoCloseable autoCloseableMocks; + + @InjectMocks() + private GovtIdentityTypeServiceImpl target; + + @AfterEach() + public void afterTest() throws Exception { + if (autoCloseableMocks != null) + autoCloseableMocks.close(); + } + + //Sapient generated method id: ${ce34b8d3-199f-378c-90eb-9ed1aef6e53c}, hash: 774ACA351D3905999668C549FB1166BC + @Test() + void getActiveIDTypesWhenObjectLengthGreaterThanOrEqualsTo3() { + /* Branches:* (for-each(resultSet)) : true* (object != null) : true* (object.length >= 3) : true*/ + //Arrange Statement(s) + target = new GovtIdentityTypeServiceImpl(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + Object[] objectArray = new Object[]{1, "A", false}; + Set<Object[]> objectSet = new HashSet<>(); + objectSet.add(objectArray); + doReturn(objectSet).when(govtIdentityTypeRepositoryMock).getActiveIDTypes(); + + //Act Statement(s) + List<GovtIdentityType> result = target.getActiveIDTypes(); + + //Assert statement(s) + assertAll("result", () -> { + assertThat(result.size(), equalTo(1)); + assertThat(result.get(0), is(instanceOf(GovtIdentityType.class))); + verify(govtIdentityTypeRepositoryMock).getActiveIDTypes(); + }); + } +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/RegisterBenificiaryServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/RegisterBenificiaryServiceImplTest.java new file mode 100644 index 00000000..a859d732 --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/RegisterBenificiaryServiceImplTest.java @@ -0,0 +1,149 @@ +package com.iemr.common.service.beneficiary; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.data.beneficiary.Beneficiary; +import com.iemr.common.dto.identity.CommonIdentityDTO; +import com.iemr.common.dto.identity.IdentityEditDTO; +import com.iemr.common.mapper.CommonIdentityMapper; +import com.iemr.common.mapper.IdentityBenEditMapper; +import com.iemr.common.mapper.utils.InputMapper; +import com.iemr.common.model.beneficiary.BeneficiaryDemographicsModel; +import com.iemr.common.model.beneficiary.BeneficiaryGenModel; +import com.iemr.common.model.beneficiary.BeneficiaryModel; +import com.iemr.common.model.userbeneficiary.BeneficiaryIdentityModel; +import com.iemr.common.repository.mctshistory.OutboundHistoryRepository; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.validator.Validator; + +import jakarta.servlet.http.HttpServletRequest; + +@ExtendWith(MockitoExtension.class) +class RegisterBenificiaryServiceImplTest { + + @InjectMocks + RegisterBenificiaryServiceImpl registerBenificiaryServiceImpl; + @Mock + CommonIdentityMapper identityMapper; + @Mock + IdentityBeneficiaryService identityBeneficiaryService; + @Mock + IdentityBenEditMapper identityBenEditMapper; + @Mock + Validator validator; + @Mock + OutboundHistoryRepository outboundHistoryRepository; + @Mock + private InputMapper inputMapper; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void testSaveBeneficiary() { + Beneficiary beneficiary = new Beneficiary(); + Beneficiary savedBeneficiary = registerBenificiaryServiceImpl.save(beneficiary); + assertNotNull(savedBeneficiary, "Saved beneficiary should not be null"); + + // Verify that no interactions happened with the mocks as the method is + verifyNoInteractions(identityMapper, identityBeneficiaryService, identityBenEditMapper, validator, + outboundHistoryRepository); + } + + @Test + void testUpdateBenificiary() throws IEMRException { + BeneficiaryModel beneficiaryModel = new BeneficiaryModel(); // Create a mock BeneficiaryModel + + String auth = "Auth"; // Mock authentication string + + List<BeneficiaryIdentityModel> beneficiaryIdentities = new ArrayList<>(); + beneficiaryIdentities.add(new BeneficiaryIdentityModel()); + beneficiaryModel.setBeneficiaryIdentities(beneficiaryIdentities); + IdentityEditDTO identityEditDTO = new IdentityEditDTO(); + when(identityBenEditMapper.BenToIdentityEditMapper(beneficiaryModel)).thenReturn(identityEditDTO); + when(identityBeneficiaryService.editIdentityEditDTO(identityEditDTO, auth, false)).thenReturn(1); + Integer actualUpdateBenificiaryResult = registerBenificiaryServiceImpl.updateBenificiary(beneficiaryModel, + auth); + verify(identityBenEditMapper).BenToIdentityEditMapper(beneficiaryModel); + verify(identityBeneficiaryService).editIdentityEditDTO(identityEditDTO, auth, false); + assertNotNull(beneficiaryIdentities); + assertEquals(1, actualUpdateBenificiaryResult.intValue()); + } + + @Test + void testSaveBeneficiaryModelHttpServletRequest() throws Exception { + + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + BeneficiaryModel beneficiaryModel = new BeneficiaryModel(); + beneficiaryModel.setIs1097(false); // Set a default value for is1097 + when(httpServletRequest.getHeader("authorization")).thenReturn("mockAuthToken"); + CommonIdentityDTO identityDTO = new CommonIdentityDTO(); + when(identityMapper.beneficiaryModelCommonIdentityDTO(beneficiaryModel)).thenReturn(identityDTO); + String identityResponse = "{\"response\":{\"data\":{\"benId\":1,\"benRegId\":123}}}"; + when(identityBeneficiaryService.getIdentityResponse(Mockito.anyString(), Mockito.anyString(), + Mockito.anyBoolean())).thenReturn(identityResponse); + String response = registerBenificiaryServiceImpl.save(beneficiaryModel, httpServletRequest); + assertNotNull(response, "Response should not be null"); + verify(identityMapper).beneficiaryModelCommonIdentityDTO(beneficiaryModel); + + verify(identityBeneficiaryService).getIdentityResponse(Mockito.anyString(), + ArgumentMatchers.eq("mockAuthToken"), ArgumentMatchers.eq(false)); + + } + + @Test + void testUpdateCommunityorEducation() throws IEMRException { + BeneficiaryModel beneficiaryModel = new BeneficiaryModel(); + beneficiaryModel.setBeneficiaryRegID(123L); + beneficiaryModel.setIs1097(false); + + BeneficiaryDemographicsModel iBenDemographics = new BeneficiaryDemographicsModel(); + iBenDemographics.setCommunityID(1); + iBenDemographics.setEducationID(2); + beneficiaryModel.setI_bendemographics(iBenDemographics); + String auth = "mockAuth"; + when(identityBeneficiaryService.editIdentityEditDTOCommunityorEducation(Mockito.any(IdentityEditDTO.class), + Mockito.eq(auth), Mockito.eq(false))).thenReturn(1); + + Integer updatedRows = registerBenificiaryServiceImpl.updateCommunityorEducation(beneficiaryModel, auth); + assertEquals(1, updatedRows); + + verify(identityBeneficiaryService).editIdentityEditDTOCommunityorEducation(Mockito.any(IdentityEditDTO.class), + Mockito.eq(auth), Mockito.eq(false)); + } + + @Test + void testGenerateBeneficiaryIDs() throws Exception { + String request = "{\"request\":{}}"; + HttpServletRequest servletRequest = mock(HttpServletRequest.class); + when(servletRequest.getHeader("authorization")).thenReturn("mockAuth"); + List<BeneficiaryGenModel> beneficiaryGenModels = new ArrayList<>(); + beneficiaryGenModels.add(new BeneficiaryGenModel()); + when(identityBeneficiaryService.generateBeneficiaryIDs(Mockito.anyString(), Mockito.eq("mockAuth"))) + .thenReturn(beneficiaryGenModels); + + String response = registerBenificiaryServiceImpl.generateBeneficiaryIDs(request, servletRequest); + assertNotNull(response, "Response should not be null"); + + } + +} diff --git a/src/test/java/com/iemr/common/service/beneficiary/SexualOrientationServiceImplTest.java b/src/test/java/com/iemr/common/service/beneficiary/SexualOrientationServiceImplTest.java new file mode 100644 index 00000000..33348305 --- /dev/null +++ b/src/test/java/com/iemr/common/service/beneficiary/SexualOrientationServiceImplTest.java @@ -0,0 +1,76 @@ +package com.iemr.common.service.beneficiary; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.beneficiary.SexualOrientation; +import com.iemr.common.repository.userbeneficiarydata.SexualOrientationRepository; + +@ExtendWith(MockitoExtension.class) +class SexualOrientationServiceImplTest { + @Mock + private SexualOrientationRepository sexualOrientationRepository; + + @InjectMocks + private SexualOrientationServiceImpl sexualOrientationServiceImpl; + + @Test + void testGetSexualOrientations() { + when(sexualOrientationRepository.findAciveOrientations()).thenReturn(new HashSet<>()); + List<SexualOrientation> actualSexualOrientations = sexualOrientationServiceImpl.getSexualOrientations(); + verify(sexualOrientationRepository).findAciveOrientations(); + assertTrue(actualSexualOrientations.isEmpty()); + } + + @Test + void testGetSexualOrientations2() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[] { "42" }); + when(sexualOrientationRepository.findAciveOrientations()).thenReturn(objectArraySet); + List<SexualOrientation> actualSexualOrientations = sexualOrientationServiceImpl.getSexualOrientations(); + verify(sexualOrientationRepository).findAciveOrientations(); + assertTrue(actualSexualOrientations.isEmpty()); + } + + @Test + void testGetSexualOrientations3() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(null); + when(sexualOrientationRepository.findAciveOrientations()).thenReturn(objectArraySet); + List<SexualOrientation> actualSexualOrientations = sexualOrientationServiceImpl.getSexualOrientations(); + verify(sexualOrientationRepository).findAciveOrientations(); + assertTrue(actualSexualOrientations.isEmpty()); + } + + @Test + void testGetSexualOrientations4() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[] { (short) 1, "42" }); + when(sexualOrientationRepository.findAciveOrientations()).thenReturn(objectArraySet); + List<SexualOrientation> actualSexualOrientations = sexualOrientationServiceImpl.getSexualOrientations(); + verify(sexualOrientationRepository).findAciveOrientations(); + assertEquals(1, actualSexualOrientations.size()); + } + + @Test + void testGetSexualOrientations5() { + HashSet<Object[]> objectArraySet = new HashSet<>(); + objectArraySet.add(new Object[] { (short) 2, "42" }); + when(sexualOrientationRepository.findAciveOrientations()).thenReturn(objectArraySet); + List<SexualOrientation> actualSexualOrientations = sexualOrientationServiceImpl.getSexualOrientations(); + verify(sexualOrientationRepository).findAciveOrientations(); + assertEquals(1, actualSexualOrientations.size()); + } +} diff --git a/src/test/java/com/iemr/common/service/brd/BRDIntegrationServiceUmplTest.java b/src/test/java/com/iemr/common/service/brd/BRDIntegrationServiceUmplTest.java new file mode 100644 index 00000000..5e3a23c3 --- /dev/null +++ b/src/test/java/com/iemr/common/service/brd/BRDIntegrationServiceUmplTest.java @@ -0,0 +1,65 @@ +package com.iemr.common.service.brd; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.beneficiary.BenRelationshipType; +import com.iemr.common.repository.beneficiary.BeneficiaryRelationshipTypeRepository; +import com.iemr.common.service.beneficiary.BenRelationshipTypeServiceImpl; + +@ExtendWith(MockitoExtension.class) +class BRDIntegrationServiceUmplTest { + + private final BeneficiaryRelationshipTypeRepository beneficiaryRelationshipTypeRepositoryMock = mock( + BeneficiaryRelationshipTypeRepository.class, "beneficiaryRelationshipTypeRepository"); + + private AutoCloseable autoCloseableMocks; + + @InjectMocks() + private BenRelationshipTypeServiceImpl target; + + @AfterEach() + public void afterTest() throws Exception { + if (autoCloseableMocks != null) + autoCloseableMocks.close(); + } + + @Test() + void getActiveRelationshipTypesWhenObjectLengthGreaterThanOrEqualsTo2() { + // Arrange Statement(s) + target = new BenRelationshipTypeServiceImpl(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + Object[] objectArray = new Object[] { 0, "return_of_getActiveRelationshipsItem1Item1" }; + Set<Object[]> objectSet = new HashSet<>(); + objectSet.add(objectArray); + doReturn(objectSet).when(beneficiaryRelationshipTypeRepositoryMock).getActiveRelationships(); + + // Act Statement(s) + List<BenRelationshipType> result = target.getActiveRelationshipTypes(); + + // Assert statement(s) + assertAll("result", () -> { + assertThat(result.size(), equalTo(1)); + assertThat(result.get(0), is(instanceOf(BenRelationshipType.class))); + verify(beneficiaryRelationshipTypeRepositoryMock).getActiveRelationships(); + }); + } +} diff --git a/src/test/java/com/iemr/common/service/callhandling/CalltypeServiceImplTest.java b/src/test/java/com/iemr/common/service/callhandling/CalltypeServiceImplTest.java new file mode 100644 index 00000000..6d6849ab --- /dev/null +++ b/src/test/java/com/iemr/common/service/callhandling/CalltypeServiceImplTest.java @@ -0,0 +1,128 @@ +package com.iemr.common.service.callhandling; + +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import com.iemr.common.utils.exception.IEMRException; +import org.json.JSONException; + +import java.util.List; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.iemr.common.data.callhandling.CallType; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Set; +import java.util.HashSet; + +import org.mockito.MockedStatic; +import com.iemr.common.repository.callhandling.IEMRCalltypeRepositoryImplCustom; +import com.iemr.common.utils.mapper.InputMapper; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.verify; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.hamcrest.Matchers.is; + +import org.junit.jupiter.api.Disabled; + +@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) +@ExtendWith(MockitoExtension.class) +class CalltypeServiceImplTest { + + private final IEMRCalltypeRepositoryImplCustom iEMRCalltypeRepositoryImplCustomMock = mock( + IEMRCalltypeRepositoryImplCustom.class, "iEMRCalltypeRepositoryImplCustom"); + + private AutoCloseable autoCloseableMocks; + + @InjectMocks() + private CalltypeServiceImpl target; + + @AfterEach() + public void afterTest() throws Exception { + if (autoCloseableMocks != null) + autoCloseableMocks.close(); + } + + @Test() + void getAllCalltypesWhenObjectIsNotNullAndObjectLengthGreaterThanOrEqualsTo8() throws IEMRException { + /* + * Branches:* (provider.getIsInbound() != null) : true* + * (provider.getIsOutbound() != null) : true* (for-each(callTypesArray)) : true* + * (object != null) : true* (object.length >= 8) : true + */ + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + CallType callType = new CallType(); + callType.setIsInbound(false); + callType.setIsOutbound(false); + callType.setProviderServiceMapID(0); + doReturn(callType).when(inputMapperMock).fromJson("request1", CallType.class); + target = new CalltypeServiceImpl(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + Object[] objectArray = new Object[] { "A", 1, "B", "C", false, false, false, false }; + Set<Object[]> objectSet = new HashSet<>(); + objectSet.add(objectArray); + doReturn(objectSet).when(iEMRCalltypeRepositoryImplCustomMock).getCallTypes(0, false, false); + // Act Statement(s) + List<CallType> result = target.getAllCalltypes("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result.size(), equalTo(1)); + assertThat(result.get(0), is(instanceOf(CallType.class))); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("request1", CallType.class); + verify(iEMRCalltypeRepositoryImplCustomMock).getCallTypes(0, false, false); + }); + } + } + + @Test() + void getAllCalltypesWhenCallTypesArrayIsNotEmptyAndObjectIsNotNullAndObjectLengthGreaterThanOrEqualsTo8() + throws IEMRException { + /* + * Branches:* (provider.getIsInbound() != null) : true* + * (provider.getIsOutbound() != null) : false* (for-each(callTypesArray)) : + * true* (object != null) : true* (object.length >= 8) : true + */ + // Arrange Statement(s) + InputMapper inputMapperMock = mock(InputMapper.class); + try (MockedStatic<InputMapper> inputMapper = mockStatic(InputMapper.class)) { + inputMapper.when(() -> InputMapper.gson()).thenReturn(inputMapperMock); + CallType callType = new CallType(); + callType.setIsOutbound((Boolean) null); + callType.setProviderServiceMapID(0); + doReturn(callType).when(inputMapperMock).fromJson("request1", CallType.class); + target = new CalltypeServiceImpl(); + autoCloseableMocks = MockitoAnnotations.openMocks(this); + Object[] objectArray = new Object[] { "A", 1, "B", "C", false, false, false, false }; + Set<Object[]> objectSet = new HashSet<>(); + objectSet.add(objectArray); + doReturn(objectSet).when(iEMRCalltypeRepositoryImplCustomMock).getCallTypes(0); + // Act Statement(s) + List<CallType> result = target.getAllCalltypes("request1"); + // Assert statement(s) + assertAll("result", () -> { + assertThat(result.size(), equalTo(1)); + assertThat(result.get(0), is(instanceOf(CallType.class))); + inputMapper.verify(() -> InputMapper.gson(), atLeast(1)); + verify(inputMapperMock).fromJson("request1", CallType.class); + verify(iEMRCalltypeRepositoryImplCustomMock).getCallTypes(0); + }); + } + } + +} diff --git a/src/test/java/com/iemr/common/service/category/CategoryServiceImplTest.java b/src/test/java/com/iemr/common/service/category/CategoryServiceImplTest.java new file mode 100644 index 00000000..6bcf050f --- /dev/null +++ b/src/test/java/com/iemr/common/service/category/CategoryServiceImplTest.java @@ -0,0 +1,61 @@ +package com.iemr.common.service.category; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.category.CategoryDetails; +import com.iemr.common.repository.category.CategoryRepository; + +@ExtendWith(MockitoExtension.class) +class CategoryServiceImplTest { + + @Mock + private CategoryRepository categoryRepository; + + @InjectMocks + private CategoryServiceImpl categoryService; + + @Test + void testGetAllCategoriesReturnsCorrectData() { + // Setup + List<CategoryDetails> expectedCategories = new ArrayList<>(); + expectedCategories.add(new CategoryDetails(1, "Health")); + expectedCategories.add(new CategoryDetails(2, "Wellness")); + + when(categoryRepository.findBy()).thenReturn((ArrayList<CategoryDetails>) expectedCategories); + + // Execution + List<CategoryDetails> result = categoryService.getAllCategories(); + + // Assertions + assertNotNull(result, "The result should not be null."); + assertEquals(expectedCategories.size(), result.size(), + "The size of the results should match the expected size."); + assertEquals(expectedCategories.get(0).getCategoryID(), result.get(0).getCategoryID(), + "The first category ID should match."); + assertEquals(expectedCategories.get(0).getCategoryName(), result.get(0).getCategoryName(), + "The first category name should match."); + assertEquals(expectedCategories.get(1).getCategoryID(), result.get(1).getCategoryID(), + "The second category ID should match."); + assertEquals(expectedCategories.get(1).getCategoryName(), result.get(1).getCategoryName(), + "The second category name should match."); + + // Verification + verify(categoryRepository, times(1)).findBy(); + } +} diff --git a/src/test/java/com/iemr/common/service/category/SubCategoryServiceImplTest.java b/src/test/java/com/iemr/common/service/category/SubCategoryServiceImplTest.java new file mode 100644 index 00000000..493fef23 --- /dev/null +++ b/src/test/java/com/iemr/common/service/category/SubCategoryServiceImplTest.java @@ -0,0 +1,54 @@ +package com.iemr.common.service.category; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.category.SubCategoryDetails; +import com.iemr.common.repository.category.SubCategoryRepository; + +@ExtendWith(MockitoExtension.class) +class SubCategoryServiceImplTest { + + @Mock + private SubCategoryRepository subCategoryRepository; + + @InjectMocks + private SubCategoryServiceImpl subCategoryService; + + @Test + void testGetSubCategoriesReturnsCorrectData() { + // Given + Integer categoryId = 1; + ArrayList<Object[]> mockData = new ArrayList<>(); + mockData.add(new Object[]{1, "SubCategory 1"}); + mockData.add(new Object[]{2, "SubCategory 2"}); + + when(subCategoryRepository.findBy(categoryId)).thenReturn(mockData); + + // When + List<SubCategoryDetails> result = subCategoryService.getSubCategories(categoryId); + + // Then + assertNotNull(result, "The result should not be null."); + assertEquals(2, result.size(), "The size of the results should match the expected size."); + assertEquals(Integer.valueOf(1), result.get(0).getSubCategoryID(), "The ID of the first sub-category should match."); + assertEquals("SubCategory 1", result.get(0).getSubCategoryName(), "The name of the first sub-category should match."); + assertEquals(Integer.valueOf(2), result.get(1).getSubCategoryID(), "The ID of the second sub-category should match."); + assertEquals("SubCategory 2", result.get(1).getSubCategoryName(), "The name of the second sub-category should match."); + + // Verify + verify(subCategoryRepository, times(1)).findBy(categoryId); + } +} diff --git a/src/test/java/com/iemr/common/service/directory/DirectoryServiceImplTest.java b/src/test/java/com/iemr/common/service/directory/DirectoryServiceImplTest.java new file mode 100644 index 00000000..c95d6730 --- /dev/null +++ b/src/test/java/com/iemr/common/service/directory/DirectoryServiceImplTest.java @@ -0,0 +1,55 @@ +package com.iemr.common.service.directory; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.directory.Directory; +import com.iemr.common.repository.directory.DirectoryRepository; + +@ExtendWith(MockitoExtension.class) +class DirectoryServiceImplTest { + + @Mock + private DirectoryRepository directoryRepository; + + @InjectMocks + private DirectoryServiceImpl directoryService; + + @Test + void getDirectories_ReturnsListOfDirectories() { + Set<Object[]> mockData = new HashSet<>(); + mockData.add(new Object[] { 1, "Directory 1" }); + mockData.add(new Object[] { 2, "Directory 2" }); + when(directoryRepository.findAciveDirectories()).thenReturn(mockData); + + List<Directory> directories = directoryService.getDirectories(); + + assertNotNull(directories); + assertEquals(2, directories.size()); + } + + @Test + void getDirectories_WithProviderServiceMapID_ReturnsFilteredDirectories() { + Integer providerServiceMapID = 100; + List<Directory> mockData = List.of(new Directory(1, "Filtered Directory")); + when(directoryRepository.findAciveDirectories(providerServiceMapID)).thenReturn(mockData); + + List<Directory> directories = directoryService.getDirectories(providerServiceMapID); + + assertNotNull(directories); + assertEquals(1, directories.size()); + assertEquals("Filtered Directory", directories.get(0).getInstituteDirectoryName()); + } + +} diff --git a/src/test/java/com/iemr/common/service/directory/SubDirectoryServiceImplTest.java b/src/test/java/com/iemr/common/service/directory/SubDirectoryServiceImplTest.java new file mode 100644 index 00000000..d42bae13 --- /dev/null +++ b/src/test/java/com/iemr/common/service/directory/SubDirectoryServiceImplTest.java @@ -0,0 +1,48 @@ +package com.iemr.common.service.directory; + +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.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.directory.SubDirectory; +import com.iemr.common.repository.directory.SubDirectoryRepository; + +@ExtendWith(MockitoExtension.class) +class SubDirectoryServiceImplTest { + + @Mock + private SubDirectoryRepository subDirectoryRepository; + + @InjectMocks + private SubDirectoryServiceImpl subDirectoryService; + + @Test + void getSubDirectories_ReturnsSubDirectoriesList() { + int directoryID = 1; + Set<Object[]> mockedResult = new HashSet<>(); + mockedResult.add(new Object[] { 10, "SubDirectory A" }); + mockedResult.add(new Object[] { 11, "SubDirectory B" }); + when(subDirectoryRepository.findAciveSubDirectories(directoryID)).thenReturn(mockedResult); + + List<SubDirectory> subDirectories = subDirectoryService.getSubDirectories(directoryID); + + assertNotNull(subDirectories, "SubDirectories list should not be null"); + assertEquals(2, subDirectories.size(), "Expected 2 subdirectories in the result"); + assertTrue(subDirectories.stream().anyMatch(sub -> "SubDirectory A".equals(sub.getInstituteSubDirectoryName())), + "SubDirectory A should be in the result list"); + assertTrue(subDirectories.stream().anyMatch(sub -> "SubDirectory B".equals(sub.getInstituteSubDirectoryName())), + "SubDirectory B should be in the result list"); + } + +} diff --git a/src/test/java/com/iemr/common/service/feedback/FeedbackRequestServiceImplTest.java b/src/test/java/com/iemr/common/service/feedback/FeedbackRequestServiceImplTest.java new file mode 100644 index 00000000..2aa20c95 --- /dev/null +++ b/src/test/java/com/iemr/common/service/feedback/FeedbackRequestServiceImplTest.java @@ -0,0 +1,57 @@ +package com.iemr.common.service.feedback; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.feedback.FeedbackRequest; +import com.iemr.common.repository.feedback.FeedbackRequestRepository; + +@ExtendWith(MockitoExtension.class) +class FeedbackRequestServiceImplTest { + + @Mock + private FeedbackRequestRepository feedbackRequestRepository; + + @InjectMocks + private FeedbackRequestServiceImpl feedbackRequestService; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testGetFeedbackRequest() { + // Given + Long feedbackRequestID = 1L; + FeedbackRequest expectedFeedbackRequest = new FeedbackRequest(); + expectedFeedbackRequest.setFeedbackRequestID(feedbackRequestID); + expectedFeedbackRequest.setFeedbackID(2L); // Additional properties as needed + + when(feedbackRequestRepository.findByFeedbackRequestID(feedbackRequestID)).thenReturn(expectedFeedbackRequest); + + // When + FeedbackRequest result = feedbackRequestService.getFeedbackReuest(feedbackRequestID); + + // Then + assertNotNull(result, "FeedbackRequest should not be null"); + assertEquals(expectedFeedbackRequest, result, "The returned FeedbackRequest does not match the expected"); + assertEquals(feedbackRequestID, result.getFeedbackRequestID(), "The FeedbackRequest ID does not match"); + + // Verify the interaction with the mocked repository + verify(feedbackRequestRepository, times(1)).findByFeedbackRequestID(feedbackRequestID); + } + +} diff --git a/src/test/java/com/iemr/common/service/feedback/FeedbackResponseServiceImplTest.java b/src/test/java/com/iemr/common/service/feedback/FeedbackResponseServiceImplTest.java new file mode 100644 index 00000000..e82e2a9b --- /dev/null +++ b/src/test/java/com/iemr/common/service/feedback/FeedbackResponseServiceImplTest.java @@ -0,0 +1,87 @@ +package com.iemr.common.service.feedback; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.google.gson.Gson; +import com.iemr.common.data.feedback.FeedbackRequest; +import com.iemr.common.data.feedback.FeedbackResponse; +import com.iemr.common.notification.exception.IEMRException; +import com.iemr.common.repository.feedback.FeedbackRequestRepository; +import com.iemr.common.repository.feedback.FeedbackResponseRepository; +import com.iemr.common.utils.mapper.InputMapper; + +@ExtendWith(MockitoExtension.class) +class FeedbackResponseServiceImplTest { + + @Mock + private FeedbackResponseRepository feedbackResponseRepository; + + @Mock + private FeedbackRequestRepository feedbackRequestRepository; + + @Mock + private InputMapper inputMapper; + + @InjectMocks + private FeedbackResponseServiceImpl service; + + @Test + void testGetFeedbackResponse() { + FeedbackResponse mockResponse = new FeedbackResponse(); + mockResponse.setFeedbackResponseID(1L); // Assuming an ID setter method exists + when(feedbackResponseRepository.findByFeedbackResponseID(1L)).thenReturn(mockResponse); + + FeedbackResponse result = service.getFeedbackResponse(1L); + + assertNotNull(result); + assertEquals(1L, result.getFeedbackResponseID()); + } + + @Test + void testCreateFeedbackResponse() { + FeedbackResponse feedbackResponse = new FeedbackResponse(); + when(feedbackResponseRepository.save(any(FeedbackResponse.class))).thenReturn(feedbackResponse); + + FeedbackResponse createdResponse = service.createFeedbackResponse(feedbackResponse); + + assertNotNull(createdResponse); + } + + @Test + void testCreateFeedbackRequest() { + FeedbackRequest feedbackRequest = new FeedbackRequest(); + when(feedbackRequestRepository.save(any(FeedbackRequest.class))).thenReturn(feedbackRequest); + + FeedbackRequest createdRequest = service.createFeedbackRequest(feedbackRequest); + + assertNotNull(createdRequest); + } + + @Test + void testGetdataById() { + Long id = 1L; + ArrayList<Object[]> mockData = new ArrayList<>(); + mockData.add(new Object[] { "Data1", "Data2" }); // Simplify to match your actual use case + when(feedbackResponseRepository.getdatabyId(id)).thenReturn(mockData); + + ArrayList<Object[]> result = service.getdataById(id); + + assertFalse(result.isEmpty()); + assertEquals(2, result.get(0).length); + } + +} diff --git a/src/test/java/com/iemr/common/service/feedback/FeedbackSeverityServiceImplTest.java b/src/test/java/com/iemr/common/service/feedback/FeedbackSeverityServiceImplTest.java new file mode 100644 index 00000000..48eacadb --- /dev/null +++ b/src/test/java/com/iemr/common/service/feedback/FeedbackSeverityServiceImplTest.java @@ -0,0 +1,65 @@ +package com.iemr.common.service.feedback; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.feedback.FeedbackSeverity; +import com.iemr.common.repository.feedback.FeedbackSeverityRepository; + +@ExtendWith(MockitoExtension.class) +class FeedbackSeverityServiceImplTest { + + @Mock + private FeedbackSeverityRepository feedbackSeverityRepository; + + @InjectMocks + private FeedbackSeverityServiceImpl feedbackSeverityService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testGetActiveFeedbackSeverity() { + Set<Object[]> mockData = new HashSet<>(); + mockData.add(new Object[] { 1, "High" }); + mockData.add(new Object[] { 2, "Medium" }); + when(feedbackSeverityRepository.getActiveFeedbackSeverity()).thenReturn(mockData); + + List<FeedbackSeverity> result = feedbackSeverityService.getActiveFeedbackSeverity(); + + assertNotNull(result); + assertEquals(2, result.size()); + verify(feedbackSeverityRepository).getActiveFeedbackSeverity(); + } + + @Test + void testGetActiveFeedbackSeverityWithProviderServiceMapID() { + Integer providerServiceMapID = 1; + List<FeedbackSeverity> mockData = List.of(new FeedbackSeverity(1, "High")); + when(feedbackSeverityRepository.getActiveFeedbackSeverity(providerServiceMapID)).thenReturn(mockData); + + List<FeedbackSeverity> result = feedbackSeverityService.getActiveFeedbackSeverity(providerServiceMapID); + + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals("High", result.get(0).getSeverityTypeName()); + verify(feedbackSeverityRepository).getActiveFeedbackSeverity(providerServiceMapID); + } + +} diff --git a/src/test/java/com/iemr/common/service/feedback/FeedbackTypeServiceImplTest.java b/src/test/java/com/iemr/common/service/feedback/FeedbackTypeServiceImplTest.java new file mode 100644 index 00000000..eaa770c1 --- /dev/null +++ b/src/test/java/com/iemr/common/service/feedback/FeedbackTypeServiceImplTest.java @@ -0,0 +1,72 @@ +package com.iemr.common.service.feedback; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.anyInt; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.feedback.FeedbackType; +import com.iemr.common.repository.feedback.FeedbackTypeRepository; + +@ExtendWith(MockitoExtension.class) +class FeedbackTypeServiceImplTest { + + @Test + void testGetActiveFeedbackTypes() { + // Initialize mocks + FeedbackTypeRepository mockRepository = Mockito.mock(FeedbackTypeRepository.class); + + // Sample data + Set<Object[]> sampleData = new HashSet<>(); + sampleData.add(new Object[] { 1, "Type 1" }); + sampleData.add(new Object[] { 2, "Type 2" }); + + // Stubbing repository + Mockito.when(mockRepository.findActiveFeedbackTypes()).thenReturn(sampleData); + + // Service initialization + FeedbackTypeServiceImpl service = new FeedbackTypeServiceImpl(); + service.setFeedbackTypeRepository(mockRepository); + + // Execute service method + List<FeedbackType> result = service.getActiveFeedbackTypes(); + + // Assertions + assertNotNull(result); + assertEquals(2, result.size()); + } + + @Test + void testGetActiveFeedbackTypesWithProviderServiceMapID() { + // Initialize mocks + FeedbackTypeRepository mockRepository = Mockito.mock(FeedbackTypeRepository.class); + Integer providerServiceMapID = 100; // Example ID + + // Sample data + List<FeedbackType> sampleData = List.of(new FeedbackType(1, "Type 1")); + + // Stubbing repository + Mockito.when(mockRepository.findActiveFeedbackTypes(anyInt())).thenReturn(sampleData); + + // Service initialization + FeedbackTypeServiceImpl service = new FeedbackTypeServiceImpl(); + service.setFeedbackTypeRepository(mockRepository); + + // Execute service method + List<FeedbackType> result = service.getActiveFeedbackTypes(providerServiceMapID); + + // Assertions + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals("Type 1", result.get(0).getFeedbackTypeName()); + } + +} diff --git a/src/test/java/com/iemr/common/service/institute/DesignationServiceImplTest.java b/src/test/java/com/iemr/common/service/institute/DesignationServiceImplTest.java new file mode 100644 index 00000000..3e8785ab --- /dev/null +++ b/src/test/java/com/iemr/common/service/institute/DesignationServiceImplTest.java @@ -0,0 +1,59 @@ +package com.iemr.common.service.institute; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.institute.Designation; +import com.iemr.common.repository.institute.DesignationRepository; + +@ExtendWith(MockitoExtension.class) +class DesignationServiceImplTest { + + @Mock + private DesignationRepository designationRepository; + + @InjectMocks + private DesignationServiceImpl designationService; + + @Test + void testGetDesignationsReturnsNonEmptyList() { + // Setup + List<Designation> mockDesignations = new ArrayList<>(); + mockDesignations.add(new Designation(1, "DesignationName")); // Assuming Designation has an id and name + when(designationRepository.findAciveDesignations()).thenReturn(mockDesignations); + + // Execute + List<Designation> result = designationService.getDesignations(); + + // Verify + verify(designationRepository).findAciveDesignations(); + assertFalse(result.isEmpty(), "The designations list should not be empty."); + assertEquals(1, result.size(), "The designations list should contain exactly one element."); + } + + @Test + void testGetDesignationsReturnsEmptyList() { + // Setup + when(designationRepository.findAciveDesignations()).thenReturn(new ArrayList<>()); + + // Execute + List<Designation> result = designationService.getDesignations(); + + // Verify + verify(designationRepository).findAciveDesignations(); + assertTrue(result.isEmpty(), "The designations list should be empty when no active designations are found."); + } + +} diff --git a/src/test/java/com/iemr/common/service/institute/InstituteServiceImplTest.java b/src/test/java/com/iemr/common/service/institute/InstituteServiceImplTest.java new file mode 100644 index 00000000..596acf49 --- /dev/null +++ b/src/test/java/com/iemr/common/service/institute/InstituteServiceImplTest.java @@ -0,0 +1,80 @@ +package com.iemr.common.service.institute; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.institute.Institute; +import com.iemr.common.repository.institute.InstituteRepository; + +@ExtendWith(MockitoExtension.class) +class InstituteServiceImplTest { + + @Mock + private InstituteRepository instituteRepository; + + @InjectMocks + private InstituteServiceImpl instituteService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void whenFindActiveInstitutesByStateDistBlockIDReturnsNonEmpty_thenSuccess() { + Set<Object[]> mockedResult = new HashSet<>(); + mockedResult.add(new Object[] { 1, "Institute A" }); + when(instituteRepository.findAciveInstitutesByStateDistBlockID(1, 1, 1)).thenReturn(mockedResult); + + List<Institute> institutes = instituteService.getInstitutesByStateDistrictBranch(1, 1, 1); + + assertFalse(institutes.isEmpty(), "Expected non-empty list of institutes"); + assertEquals(1, institutes.size(), "Expected list size to be 1"); + } + + @Test + void whenFindActiveInstitutesByStateDistBlockIDReturnsEmpty_thenSuccess() { + when(instituteRepository.findAciveInstitutesByStateDistBlockID(1, 1, 1)).thenReturn(new HashSet<>()); + + List<Institute> institutes = instituteService.getInstitutesByStateDistrictBranch(1, 1, 1); + + assertTrue(institutes.isEmpty(), "Expected an empty list of institutes"); + } + + // + @Test + void whenFindActiveInstitutesByBranchIDReturnsNonEmpty_thenSuccess() { + Set<Object[]> mockedResult = new HashSet<>(); + mockedResult.add(new Object[] { 2, "Institute B" }); + when(instituteRepository.findAciveInstitutesByBranchID(1)).thenReturn(mockedResult); + + List<Institute> institutes = instituteService.getInstitutesByBranch(1); + + assertFalse(institutes.isEmpty(), "Expected non-empty list of institutes"); + assertEquals(1, institutes.size(), "Expected list size to be 1"); + } + + @Test + void whenFindActiveInstitutesByBranchIDReturnsEmpty_thenSuccess() { + when(instituteRepository.findAciveInstitutesByBranchID(1)).thenReturn(new HashSet<>()); + + List<Institute> institutes = instituteService.getInstitutesByBranch(1); + + assertTrue(institutes.isEmpty(), "Expected an empty list of institutes"); + } + +} diff --git a/src/test/java/com/iemr/common/service/institute/InstituteTypeServiceImplTest.java b/src/test/java/com/iemr/common/service/institute/InstituteTypeServiceImplTest.java new file mode 100644 index 00000000..105134cc --- /dev/null +++ b/src/test/java/com/iemr/common/service/institute/InstituteTypeServiceImplTest.java @@ -0,0 +1,131 @@ +package com.iemr.common.service.institute; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.anyInt; +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 java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.institute.Institute; +import com.iemr.common.data.institute.InstituteType; +import com.iemr.common.repository.institute.InstituteRepository; +import com.iemr.common.repository.institute.InstituteTypeRepository; +import com.iemr.common.utils.mapper.InputMapper; + +@ExtendWith(MockitoExtension.class) +class InstituteTypeServiceImplTest { + + @Mock + private InstituteTypeRepository instituteTypeRepository; + + @Mock + private InstituteRepository instituteRepository; + + @Mock + private InputMapper inputMapper; + + @InjectMocks + private InstituteTypeServiceImpl instituteTypeService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testGetInstitutionTypesWithNonNullProviderServiceMapID() throws Exception { + String instituteTypeRequest = "{\"providerServiceMapID\":1}"; + InstituteType mockInstituteType = new InstituteType(); + mockInstituteType.setProviderServiceMapID(1); + + List<InstituteType> mockResult = new ArrayList<>(); + mockResult.add(new InstituteType()); // Add mock data as per your requirement + + // when(inputMapper.gson()).thenReturn(new Gson()); + when(instituteTypeRepository.findAciveInstitutesTypes(1)).thenReturn(mockResult); + + List<InstituteType> result = instituteTypeService.getInstitutionTypes(instituteTypeRequest); + + assertFalse(result.isEmpty()); + verify(instituteTypeRepository).findAciveInstitutesTypes(1); + } + + @Test + void testGetInstitutionTypesWithoutProviderServiceMapID() throws Exception { + // Assuming the instituteTypeRequest does not contain a providerServiceMapID or + // it's null + String instituteTypeRequest = "{}"; // No providerServiceMapID provided + List<InstituteType> mockResult = new ArrayList<>(); + InstituteType mockInstituteType1 = new InstituteType(); + mockInstituteType1.setInstitutionTypeID(1); + mockInstituteType1.setInstitutionType("Type A"); + mockInstituteType1.setInstitutionTypeDesc("TypeDescA"); + + InstituteType mockInstituteType2 = new InstituteType(); + mockInstituteType2.setInstitutionTypeID(2); + mockInstituteType2.setInstitutionType("Type B"); + mockInstituteType2.setInstitutionTypeDesc("TypeDescB"); + + mockResult.add(mockInstituteType1); + mockResult.add(mockInstituteType2); + + when(instituteTypeRepository.findAciveInstitutesTypes()).thenReturn(mockResult); + + // Execute the test method + List<InstituteType> result = instituteTypeService.getInstitutionTypes(instituteTypeRequest); + + assertNotNull(result); + assertFalse(result.isEmpty()); + assertEquals(2, result.size()); // Expecting 2 institute types based on the mocked data + + verify(instituteTypeRepository, times(1)).findAciveInstitutesTypes(); + + verify(instituteTypeRepository, never()).findAciveInstitutesTypes(anyInt()); + } + + @Test + void testGetInstitutionName() throws Exception { + Integer institutionTypeID = 1; + ArrayList<Object[]> mockResult = new ArrayList<>(); + mockResult.add(new Object[] { 1, "Institute A" }); + + when(instituteRepository.getInstitutionNameByType(institutionTypeID)).thenReturn(mockResult); + + List<Institute> result = instituteTypeService.getInstitutionName(institutionTypeID); + + assertFalse(result.isEmpty()); + assertEquals("Institute A", result.get(0).getInstitutionName()); + } + + @Test + void testGetInstitutionNameByTypeAndDistrict() throws Exception { + Integer institutionTypeID = 1; + Integer districtID = 1; + ArrayList<Object[]> mockResult = new ArrayList<>(); + mockResult.add(new Object[] { 1, "Institute B" }); + + when(instituteRepository.getInstitutionNameByTypeAndDistrict(institutionTypeID, districtID)) + .thenReturn(mockResult); + + List<Institute> result = instituteTypeService.getInstitutionNameByTypeAndDistrict(institutionTypeID, + districtID); + + assertFalse(result.isEmpty()); + assertEquals("Institute B", result.get(0).getInstitutionName()); + } + +} diff --git a/src/test/java/com/iemr/common/service/location/LocationServiceImplTest.java b/src/test/java/com/iemr/common/service/location/LocationServiceImplTest.java new file mode 100644 index 00000000..12f2e82e --- /dev/null +++ b/src/test/java/com/iemr/common/service/location/LocationServiceImplTest.java @@ -0,0 +1,292 @@ +package com.iemr.common.service.location; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.data.location.CityDetails; +import com.iemr.common.data.location.Country; +import com.iemr.common.data.location.DistrictBlock; +import com.iemr.common.data.location.DistrictBranchMapping; +import com.iemr.common.data.location.Districts; +import com.iemr.common.data.location.States; +import com.iemr.common.repository.location.LocationCityRepository; +import com.iemr.common.repository.location.LocationCountryRepository; +import com.iemr.common.repository.location.LocationDistrictBlockRepository; +import com.iemr.common.repository.location.LocationDistrictRepository; +import com.iemr.common.repository.location.LocationDistrilctBranchRepository; +import com.iemr.common.repository.location.LocationStateRepository; + +@ExtendWith(MockitoExtension.class) +class LocationServiceImplTest { + + @InjectMocks + LocationServiceImpl locationService; + + @Mock + private LocationStateRepository locationStateRepository; + + @Mock + private LocationDistrictRepository locationDistrictRepository; + + @Mock + private LocationDistrictBlockRepository locationDistrictBlockRepository; + + @Mock + private LocationDistrilctBranchRepository locationDistrilctBranchRepository; + + @Mock + private LocationCityRepository locationCityRepository; + + @Mock + private LocationCountryRepository locationCountryRepository; + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Test + void testGetStatesReturnsNonEmptyList() { + // Setup + int testId = 1; + ArrayList<Object[]> mockResponse = new ArrayList<>(); + mockResponse.add(new Object[] { 1, "StateName" }); + when(locationStateRepository.findBy(testId)).thenReturn(mockResponse); + + // Execution + List<States> result = locationService.getStates(testId); + + // Verification + verify(locationStateRepository).findBy(testId); + assertEquals(1, result.size()); // Expecting one state in the list + } + + @Test + void testGetStatesReturnsEmptyListForNoResults() { + // Setup + int testId = 2; + ArrayList<Object[]> mockResponse = new ArrayList<>(); + when(locationStateRepository.findBy(testId)).thenReturn(mockResponse); + + // Execution + List<States> result = locationService.getStates(testId); + + // Verification + verify(locationStateRepository).findBy(testId); + assertTrue(result.isEmpty()); // The list should be empty + } + + @Test + void testGetDistrictsReturnsNonEmptyList() { + // Setup + int testId = 1; + ArrayList<Object[]> mockResponse = new ArrayList<>(); + mockResponse.add(new Object[] { 1, "DistrictName" }); // Mock data + when(locationDistrictRepository.findBy(testId)).thenReturn(mockResponse); + + // Execute + List<Districts> result = locationService.getDistricts(testId); + + // Verify + verify(locationDistrictRepository).findBy(testId); + assertFalse(result.isEmpty(), "The district list should not be empty."); + assertEquals(1, result.size(), "The district list should contain exactly one element."); + } + + @Test + void testGetDistrictsReturnsEmptyListForNoResults() { + // Setup + int testId = 99; // Assuming this ID will return no results + when(locationDistrictRepository.findBy(testId)).thenReturn(new ArrayList<>()); + + // Execute + List<Districts> result = locationService.getDistricts(testId); + + // Verify + verify(locationDistrictRepository).findBy(testId); + assertTrue(result.isEmpty(), "The district list should be empty for no results."); + } + + @Test + void testGetDistrictBlocksReturnsNonEmptyList() { + // Setup + int testId = 1; + Set<Object[]> mockResponse = new HashSet<>(); + mockResponse.add(new Object[] { 1, "BlockName" }); // Mock data + when(locationDistrictBlockRepository.findBy(testId)).thenReturn(mockResponse); + + // Execute + List<DistrictBlock> result = locationService.getDistrictBlocks(testId); + + // Verify + verify(locationDistrictBlockRepository).findBy(testId); + assertFalse(result.isEmpty(), "The district block list should not be empty."); + assertEquals(1, result.size(), "The district block list should contain exactly one element."); + } + + @Test + void testGetDistrictBlocksReturnsEmptyListForNoResults() { + // Setup + int testId = 99; // Assuming this ID will return no results + when(locationDistrictBlockRepository.findBy(testId)).thenReturn(new HashSet<>()); + + // Execute + List<DistrictBlock> result = locationService.getDistrictBlocks(testId); + + // Verify + verify(locationDistrictBlockRepository).findBy(testId); + assertTrue(result.isEmpty(), "The district block list should be empty for no results."); + } + + @Test + void testFindStateDistrictByReturnsNonEmptyList() { + // Setup + int testId = 1; + ArrayList<Object[]> mockResponse = new ArrayList<>(); + mockResponse.add(new Object[] { 1, "DistrictName", "StateName", 10 }); // Mock data + when(locationDistrictRepository.findStateDistrictBy(testId)).thenReturn(mockResponse); + + // Execute + List<Districts> result = locationService.findStateDistrictBy(testId); + + // Verify + verify(locationDistrictRepository).findStateDistrictBy(testId); + assertFalse(result.isEmpty(), "The state district list should not be empty."); + assertEquals(1, result.size(), "The state district list should contain exactly one element."); + } + + @Test + void testFindStateDistrictByReturnsEmptyListForNoResults() { + // Setup + int testId = 99; // Assuming this ID will return no results + when(locationDistrictRepository.findStateDistrictBy(testId)).thenReturn(new ArrayList<>()); + + // Execute + List<Districts> result = locationService.findStateDistrictBy(testId); + + // Verify + verify(locationDistrictRepository).findStateDistrictBy(testId); + assertTrue(result.isEmpty(), "The state district list should be empty for no results."); + } + + @Test + void testGetCitiesReturnsNonEmptyList() { + // Setup + int testId = 1; + Set<Object[]> mockResponse = new HashSet<>(); + mockResponse.add(new Object[] { 1, "CityName" }); // Mock data + when(locationDistrictBlockRepository.findBy(testId)).thenReturn(mockResponse); + + // Execute + List<CityDetails> result = locationService.getCities(testId); + + // Verify + verify(locationDistrictBlockRepository).findBy(testId); + assertFalse(result.isEmpty(), "The city list should not be empty."); + assertEquals(1, result.size(), "The city list should contain exactly one element."); + } + + @Test + void testGetCitiesReturnsEmptyListForNoResults() { + // Setup + int testId = 99; // Assuming this ID will return no results + when(locationDistrictBlockRepository.findBy(testId)).thenReturn(new HashSet<>()); + + // Execute + List<CityDetails> result = locationService.getCities(testId); + + // Verify + verify(locationDistrictBlockRepository).findBy(testId); + assertTrue(result.isEmpty(), "The city list should be empty for no results."); + } + + @Test + void testGetDistrilctBranchsReturnsNonEmptyList() { + // Setup + int testId = 1; + ArrayList<Object[]> mockResponse = new ArrayList<>(); + mockResponse.add(new Object[] { 1, "BranchName", "BranchCode", "BranchAddress", "BranchType" }); // Mock data + when(locationDistrilctBranchRepository.findAllBy(testId)).thenReturn(mockResponse); + + // Execute + List<DistrictBranchMapping> result = locationService.getDistrilctBranchs(testId); + + // Verify + verify(locationDistrilctBranchRepository).findAllBy(testId); + assertFalse(result.isEmpty(), "The distrilct branches list should not be empty."); + assertEquals(1, result.size(), "The distrilct branches list should contain exactly one element."); + } + + @Test + void testGetDistrilctBranchsReturnsEmptyListForNoResults() { + // Setup + int testId = 99; // Assuming this ID will return no results + when(locationDistrilctBranchRepository.findAllBy(testId)).thenReturn(new ArrayList<>()); + + // Execute + List<DistrictBranchMapping> result = locationService.getDistrilctBranchs(testId); + + // Verify + verify(locationDistrilctBranchRepository).findAllBy(testId); + assertTrue(result.isEmpty(), "The distrilct branches list should be empty for no results."); + } + + @Test + void testGetDistrilctBranchsIgnoresIncompleteData() { + // Setup + int testId = 2; + ArrayList<Object[]> mockResponse = new ArrayList<>(); + mockResponse.add(new Object[] { 1, "BranchName" }); // Insufficient data + when(locationDistrilctBranchRepository.findAllBy(testId)).thenReturn(mockResponse); + + // Execute + List<DistrictBranchMapping> result = locationService.getDistrilctBranchs(testId); + + // Verify + verify(locationDistrilctBranchRepository).findAllBy(testId); + assertTrue(result.isEmpty(), "The distrilct branches list should be empty when data is incomplete."); + } + + @Test + void testGetCountriesReturnsNonEmptyList() { + // Setup + List<Country> mockCountries = new ArrayList<>(); + mockCountries.add(new Country()); // Assuming Country has an id and name + when(locationCountryRepository.findAll()).thenReturn(mockCountries); + + // Execute + List<Country> countries = locationService.getCountries(); + + // Verify + verify(locationCountryRepository).findAll(); + assertFalse(countries.isEmpty(), "The country list should not be empty."); + assertEquals(1, countries.size(), "The country list should contain exactly one element."); + } + + @Test + void testGetCountriesReturnsEmptyListWhenNoCountriesFound() { + // Setup + when(locationCountryRepository.findAll()).thenReturn(new ArrayList<>()); + + // Execute + List<Country> countries = locationService.getCountries(); + + // Verify + verify(locationCountryRepository).findAll(); + assertTrue(countries.isEmpty(), "The country list should be empty when no countries are found."); + } + +} diff --git a/src/test/java/com/iemr/common/service/lonic/LonicServiceImplTest.java b/src/test/java/com/iemr/common/service/lonic/LonicServiceImplTest.java new file mode 100644 index 00000000..05e7b1ae --- /dev/null +++ b/src/test/java/com/iemr/common/service/lonic/LonicServiceImplTest.java @@ -0,0 +1,52 @@ +package com.iemr.common.service.lonic; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; + +import com.iemr.common.data.lonic.LonicDescription; +import com.iemr.common.repository.lonic.LonicRepository; + +@ExtendWith(MockitoExtension.class) +class LonicServiceImplTest { + + @Mock + private LonicRepository lonicRepository; + + @InjectMocks + private LonicServiceImpl lonicService; + + private static final int LONIC_PAGE_SIZE = 10; // Assuming this is the value in application.properties for + // lonicPageSize + + @Test + void testFindLonicRecordList_Failure_InvalidRequest() { + LonicDescription lonicDescription = new LonicDescription(); // term and pageNo are null + + Exception exception = assertThrows(Exception.class, () -> { + lonicService.findLonicRecordList(lonicDescription); + }); + + String expectedMessage = "invalid request"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); + } + +} diff --git a/src/test/java/com/iemr/common/service/questionconfig/QuestionTypeServiceImplTest.java b/src/test/java/com/iemr/common/service/questionconfig/QuestionTypeServiceImplTest.java new file mode 100644 index 00000000..448d1fc9 --- /dev/null +++ b/src/test/java/com/iemr/common/service/questionconfig/QuestionTypeServiceImplTest.java @@ -0,0 +1,55 @@ +package com.iemr.common.service.questionconfig; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.questionconfig.QuestionTypeDetail; +import com.iemr.common.notification.exception.IEMRException; +import com.iemr.common.repository.questionconfig.QuestionTypeRepository; + +@ExtendWith(MockitoExtension.class) +class QuestionTypeServiceImplTest { + + @InjectMocks + private QuestionTypeServiceImpl questionTypeService; + + @Mock + private QuestionTypeRepository questionTypeRepository; + + @Test + void testCreateQuestionType() throws IEMRException, com.iemr.common.utils.exception.IEMRException { + // Given + String jsonInput = "[{\"id\":1,\"type\":\"Multiple Choice\",\"description\":\"Choose one or more from a list.\"}]"; + QuestionTypeDetail questionTypeDetail = new QuestionTypeDetail(); // Populate with appropriate values + questionTypeDetail.setQuestionTypeID(1L); + questionTypeDetail.setQuestionType("Multiple Choice"); + questionTypeDetail.setQuestionTypeDesc("Choose one or more from a list."); + + when(questionTypeRepository.save(any(QuestionTypeDetail.class))).thenReturn(questionTypeDetail); + + // When + String result = questionTypeService.createQuestionType(jsonInput); + + // Then + assertNotNull(result); + } + + @Test + void testGetQuestionTypeList() { + assertEquals(questionTypeRepository.getQuestionTypeList().toString(), + questionTypeService.getQuestionTypeList().toString()); + } + +} diff --git a/src/test/java/com/iemr/common/service/questionconfig/QuestionnaireServiceImplTest.java b/src/test/java/com/iemr/common/service/questionconfig/QuestionnaireServiceImplTest.java new file mode 100644 index 00000000..e436d92f --- /dev/null +++ b/src/test/java/com/iemr/common/service/questionconfig/QuestionnaireServiceImplTest.java @@ -0,0 +1,55 @@ +package com.iemr.common.service.questionconfig; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.questionconfig.QuestionnaireDetail; +import com.iemr.common.notification.exception.IEMRException; +import com.iemr.common.repository.questionconfig.QuestionnaireRepository; + +@ExtendWith(MockitoExtension.class) +class QuestionnaireServiceImplTest { + + @InjectMocks + private QuestionnaireServiceImpl questionnaireService; + + @Mock + private QuestionnaireRepository questionnaireRepository; + + @Test + void testCreateQuestionnaire() throws IEMRException, com.iemr.common.utils.exception.IEMRException { + // Given + String jsonInput = "[{\"id\":1,\"name\":\"Survey 1\",\"description\":\"A sample survey.\"}]"; + QuestionnaireDetail detail = new QuestionnaireDetail(); + + detail.setQuestionID(1L); + detail.setQuestion("Survey 1"); + detail.setQuestionDesc("A sample survey."); + + when(questionnaireRepository.save(any(QuestionnaireDetail.class))).thenReturn(detail); + + // When + String result = questionnaireService.createQuestionnaire(jsonInput); + + // Then + assertNotNull(result); + } + + @Test + void testGetQuestionnaireList() { + assertEquals(questionnaireRepository.getQuestionnaireList().toString(), + questionnaireService.getQuestionnaireList().toString()); + } + +} diff --git a/src/test/java/com/iemr/common/service/scheme/SchemeServiceImplTest.java b/src/test/java/com/iemr/common/service/scheme/SchemeServiceImplTest.java new file mode 100644 index 00000000..6b6e3b69 --- /dev/null +++ b/src/test/java/com/iemr/common/service/scheme/SchemeServiceImplTest.java @@ -0,0 +1,132 @@ +package com.iemr.common.service.scheme; + +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.ArgumentMatchers.anyString; +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 java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.kmfilemanager.KMFileManager; +import com.iemr.common.data.scheme.Scheme; +import com.iemr.common.repository.scheme.SchemeRepository; +import com.iemr.common.service.kmfilemanager.KMFileManagerService; + +@ExtendWith(MockitoExtension.class) +class SchemeServiceImplTest { + + @InjectMocks + private SchemeServiceImpl schemeService; + + @Mock + private SchemeRepository schemeRepository; + + @Mock + private KMFileManagerService kmFileManagerService; + + @Test + void testGetSchemeList() throws Exception { + // Given + Integer providerServiceMapID = 1; // Example ID + List<Object[]> mockedResult = new ArrayList<>(); + mockedResult.add(new Object[] { 1, "Scheme Name", "Description", 100, 200, true, "Additional Info", + new KMFileManager() }); + // Assuming KMFileManager is a class you have. Adjust as necessary. + + when(schemeRepository.getschemeList(providerServiceMapID)).thenReturn(mockedResult); + // Mock the getFilePath if necessary + // when(yourService.getFilePath(any(KMFileManager.class))).thenReturn("path/to/file"); + + // When + List<Scheme> result = schemeService.getSchemeList(providerServiceMapID); + + // Then + assertEquals(1, result.size()); + Scheme resultScheme = result.get(0); + assertEquals("Scheme Name", resultScheme.getSchemeName()); + // Continue assertions as necessary to validate all fields + + // Verify interactions + verify(schemeRepository).getschemeList(providerServiceMapID); + // Add any necessary verification for getFilePath if it's called + } + + @Test + void testGetSchemeByID() throws Exception { + Integer schemeID = 1; + + assertEquals(schemeRepository.getSchemeByID(schemeID), schemeService.getSchemeByID(schemeID)); + + } + + @Test + void testDeletedData() { + // Given + Scheme deleteData = new Scheme(); // Assuming Scheme is a class with appropriate constructors or setters + // Populate the Scheme object as necessary for your test + + // When + String result = schemeService.deletedata(deleteData); + + // Then + assertEquals("success", result); + verify(schemeRepository, times(1)).save(deleteData); + } + + @Test + void testGetFilePath() { + // Setup + KMFileManager kmFileManager = new KMFileManager(); + kmFileManager.setFileUID("uniqueFileIdentifier"); + + // Assuming these are the properties you have set for the test environment + // or you have a way to ensure ConfigProperties returns these values during + // testing + String expectedProtocol = "http"; + String expectedPath = "example.com"; + String expectedUser = "user"; + String expectedPassword = "pass"; + String expectedUID = "uniqueFileIdentifier"; + + // Expected URI format based on the method logic + String expectedURI = String.format("%s://%s:%s@%s/Download?uuid=%s", expectedProtocol, expectedUser, + expectedPassword, expectedPath, expectedUID); + + // Execute + String resultURI = schemeService.getFilePath(kmFileManager); + + // Assert + + assertTrue(resultURI.contains("http://guest:guest@null")); + // assertEquals(expectedURI, resultURI); + } + + @Test + void testSaveSchemeWithoutKMFileManager() throws Exception { + Scheme inputScheme = new Scheme(); // KMFileManager not set + + Scheme expectedScheme = new Scheme(); + expectedScheme.setSchemeID(1); + when(schemeRepository.save(any(Scheme.class))).thenReturn(expectedScheme); + + Scheme result = schemeService.save(inputScheme); + + assertNotNull(result); + assertEquals(1, result.getSchemeID()); + verify(kmFileManagerService, never()).addKMFile(anyString()); + verify(schemeRepository, times(1)).save(any(Scheme.class)); + } + +} diff --git a/src/test/java/com/iemr/common/service/services/CommonServiceImplTest.java b/src/test/java/com/iemr/common/service/services/CommonServiceImplTest.java new file mode 100644 index 00000000..0856b528 --- /dev/null +++ b/src/test/java/com/iemr/common/service/services/CommonServiceImplTest.java @@ -0,0 +1,85 @@ +package com.iemr.common.service.services; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.anyInt; +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 static org.mockito.BDDMockito.*; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.category.CategoryDetails; +import com.iemr.common.data.category.SubCategoryDetails; +import com.iemr.common.repository.category.CategoryRepository; +import com.iemr.common.repository.category.SubCategoryRepository; +import com.iemr.common.repository.kmfilemanager.KMFileManagerRepository; +import com.iemr.common.repository.services.ServiceTypeRepository; +import com.iemr.common.utils.exception.IEMRException; +import com.iemr.common.utils.mapper.InputMapper; + +@ExtendWith(MockitoExtension.class) +class CommonServiceImplTest { + + @InjectMocks + CommonServiceImpl commonService; + + @Mock + private ServiceTypeRepository serviceTypeRepository; + @Mock + private CategoryRepository categoryRepository; + @Mock + private SubCategoryRepository subCategoryRepository; + @Mock + private KMFileManagerRepository kmFileManagerRepository; + @Mock + private InputMapper inputMapper = new InputMapper(); + + @Test + void testGetCategoriesReturnsData() { + // Local setup for this test case + List<CategoryDetails> localMockCategories = new ArrayList<>(); + localMockCategories.add(new CategoryDetails(1, "Category 1")); + localMockCategories.add(new CategoryDetails(2, "Category 2")); + + // Setup our mock repository + when(categoryRepository.findBy()).thenReturn((ArrayList<CategoryDetails>) localMockCategories); + + // Execute the service call + Iterable<CategoryDetails> categories = commonService.getCategories(); + + // Assert the response + List<CategoryDetails> resultList = new ArrayList<>(); + categories.forEach(resultList::add); + assertEquals(2, resultList.size()); + assertEquals(localMockCategories, resultList); + } + + @Test + void testGetCategoriesReturnsEmptyList() { + // Local setup for this test case with an empty list + List<CategoryDetails> localEmptyList = new ArrayList<>(); + + // Setup our mock repository to return an empty list + when(categoryRepository.findBy()).thenReturn((ArrayList<CategoryDetails>) localEmptyList); + + // Execute the service call + Iterable<CategoryDetails> categories = commonService.getCategories(); + + // Assert the response + List<CategoryDetails> resultList = new ArrayList<>(); + categories.forEach(resultList::add); + assertEquals(0, resultList.size()); + } + +} diff --git a/src/test/java/com/iemr/common/service/services/ServicesImplTest.java b/src/test/java/com/iemr/common/service/services/ServicesImplTest.java new file mode 100644 index 00000000..02e44c7e --- /dev/null +++ b/src/test/java/com/iemr/common/service/services/ServicesImplTest.java @@ -0,0 +1,62 @@ +package com.iemr.common.service.services; + +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.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.users.ServiceMaster; +import com.iemr.common.repository.services.ServiesRepository; + +@ExtendWith(MockitoExtension.class) +class ServicesImplTest { + + @InjectMocks + private ServicesImpl services; + + @Mock + private ServiesRepository serviesRepository; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void servicesListReturnsCorrectData() { + // Arrange + Set<Object[]> mockData = new HashSet<>(); + mockData.add(new Object[] { 1, "Service A", "Description A", true }); + mockData.add(new Object[] { 2, "Service B", "Description B", false }); // Assuming you handle inactive services + // somehow in your real method + + when(serviesRepository.getActiveServicesList()).thenReturn(mockData); + + // Act + List<ServiceMaster> result = services.servicesList(); + + // Assert + assertNotNull(result); + assertEquals(2, result.size()); // Assuming your real method includes inactive services in the list + assertTrue(result.stream().anyMatch(service -> service.getServiceName().equals("Service A"))); + assertTrue(result.stream().anyMatch(service -> service.getServiceName().equals("Service B"))); + + // Verify that getActiveServicesList() was called exactly once + verify(serviesRepository, times(1)).getActiveServicesList(); + } + +} diff --git a/src/test/java/com/iemr/common/service/sms/SMSServiceImplTest.java b/src/test/java/com/iemr/common/service/sms/SMSServiceImplTest.java new file mode 100644 index 00000000..1aa08fdf --- /dev/null +++ b/src/test/java/com/iemr/common/service/sms/SMSServiceImplTest.java @@ -0,0 +1,223 @@ +package com.iemr.common.service.sms; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.iemr.common.data.sms.SMSTemplate; +import com.iemr.common.data.sms.SMSType; +import com.iemr.common.mapper.sms.SMSMapper; +import com.iemr.common.model.sms.SMSRequest; +import com.iemr.common.model.sms.SMSTemplateResponse; +import com.iemr.common.model.sms.SMSTypeModel; +import com.iemr.common.model.sms.UpdateSMSRequest; +import com.iemr.common.repository.callhandling.TCRequestModelRepo; +import com.iemr.common.repository.feedback.FeedbackRepository; +import com.iemr.common.repository.helpline104history.PrescribedDrugRepository; +import com.iemr.common.repository.institute.InstituteRepository; +import com.iemr.common.repository.location.LocationDistrictBlockRepository; +import com.iemr.common.repository.location.LocationDistrictRepository; +import com.iemr.common.repository.location.LocationStateRepository; +import com.iemr.common.repository.mctshistory.OutboundHistoryRepository; +import com.iemr.common.repository.sms.SMSNotificationRepository; +import com.iemr.common.repository.sms.SMSParameterMapRepository; +import com.iemr.common.repository.sms.SMSParameterRepository; +import com.iemr.common.repository.sms.SMSTemplateRepository; +import com.iemr.common.repository.sms.SMSTypeRepository; +import com.iemr.common.repository.users.IEMRUserRepositoryCustom; +import com.iemr.common.service.beneficiary.IEMRSearchUserService; +import com.iemr.common.utils.config.ConfigProperties; +import com.iemr.common.utils.http.HttpUtils; + +@ExtendWith(MockitoExtension.class) +class SMSServiceImplTest { + + @InjectMocks + private SMSServiceImpl smsService; + + @Mock + private SMSMapper smsMapper; + + @Mock + private SMSTemplateRepository smsTemplateRepository; + + @Mock + SMSTypeRepository smsTypeRepository; + + @Mock + SMSParameterRepository smsParameterRepository; + + @Mock + SMSParameterMapRepository smsParameterMapRepository; + + @Mock + IEMRSearchUserService searchBeneficiary; + + @Mock + InstituteRepository instituteRepository; + + @Mock + IEMRUserRepositoryCustom userRepository; + + @Mock + FeedbackRepository feedbackReporsitory; + + @Mock + SMSNotificationRepository smsNotification; + + @Mock + LocationStateRepository stateRepository; + + @Mock + LocationDistrictRepository districtRepository; + + @Mock + LocationDistrictBlockRepository blockRepository; + + @Mock + HttpUtils httpUtils; + + @Mock + PrescribedDrugRepository prescribedDrugRepository; + + @Mock + OutboundHistoryRepository outboundHistoryRepository; + + private String prescription; + + private TCRequestModelRepo tCRequestModelRepo; + Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + private static Boolean publishingSMS = false; + private static final String SMS_GATEWAY_URL = ConfigProperties.getPropertyByName("sms-gateway-url"); + + @Test + void testGetSMSTemplates_smsTypeIDNull() throws Exception { + // Arrange + SMSRequest smsRequest = new SMSRequest(); + smsRequest.setProviderServiceMapID(123); + + SMSTemplate request = new SMSTemplate(); + given(smsMapper.requestToSMSTemplate(smsRequest)).willReturn(request); + + // Add these lines to initialize smsTemplate1 and smsTemplate2 + SMSTemplate smsTemplate1 = new SMSTemplate(); + smsTemplate1.setSmsTemplateID(1); + + SMSTemplate smsTemplate2 = new SMSTemplate(); + smsTemplate2.setSmsTemplateID(1); + + List<SMSTemplate> smsTemplates = Arrays.asList(smsTemplate1, smsTemplate2); + given(smsTemplateRepository.getSMSTemplateByProviderServiceMapIDOrderByDeletedSmsTypeIDDesc(null)) + .willReturn(smsTemplates); + + // Act + String result = smsService.getSMSTemplates(smsRequest); + + // Assert + assertNotNull(result); + } + + @Test + void updateSMSTemplateSuccess() throws Exception { + // Given + UpdateSMSRequest smsRequest = new UpdateSMSRequest(); // Populate with test data as needed + SMSTemplate requestTemplate = new SMSTemplate(); // Populate with test data as needed + SMSTemplate updatedTemplate = new SMSTemplate(); // Populate with expected result data + when(smsMapper.updateRequestToSMSTemplate(smsRequest)).thenReturn(requestTemplate); + when(smsTemplateRepository.updateSMSTemplate(requestTemplate.getSmsTemplateID(), requestTemplate.getDeleted())) + .thenReturn(1); + when(smsTemplateRepository.findBySmsTemplateID(requestTemplate.getSmsTemplateID())).thenReturn(updatedTemplate); + when(smsMapper.smsTemplateToResponse(updatedTemplate)).thenReturn(new SMSTemplateResponse()); // Assuming a + // response type + + // When + String result = smsService.updateSMSTemplate(smsRequest); + + // Then + assertNotNull(result); + // Additional assertions as needed, possibly checking for specific fields in the + // result + + // Verify interactions + verify(smsMapper).updateRequestToSMSTemplate(smsRequest); + verify(smsTemplateRepository).updateSMSTemplate(requestTemplate.getSmsTemplateID(), + requestTemplate.getDeleted()); + verify(smsTemplateRepository).findBySmsTemplateID(requestTemplate.getSmsTemplateID()); + } + + @Test + void updateSMSTemplateFailure() { + // Given + UpdateSMSRequest smsRequest = new UpdateSMSRequest(); // Populate as needed + SMSTemplate requestTemplate = new SMSTemplate(); // Populate as needed + when(smsMapper.updateRequestToSMSTemplate(smsRequest)).thenReturn(requestTemplate); + when(smsTemplateRepository.updateSMSTemplate(requestTemplate.getSmsTemplateID(), requestTemplate.getDeleted())) + .thenReturn(0); + + // When/Then + Exception exception = assertThrows(Exception.class, () -> { + smsService.updateSMSTemplate(smsRequest); + }); + + // Assert + assertEquals("Failed to update the result", exception.getMessage()); + + // Verify interactions + verify(smsMapper).updateRequestToSMSTemplate(smsRequest); + verify(smsTemplateRepository).updateSMSTemplate(requestTemplate.getSmsTemplateID(), + requestTemplate.getDeleted()); + verifyNoMoreInteractions(smsTemplateRepository); // No further interactions after update attempt + } + + @Test + void getSMSTypesSuccess() throws Exception { + // Given + SMSTypeModel requestModel = new SMSTypeModel(); // Setup your model + requestModel.setServiceID(1); // Example service ID + SMSType smsType = new SMSType(); // Your entity + List<SMSType> smsTypes = new ArrayList<>(); + smsTypes.add(smsType); + + List<SMSTypeModel> expectedModels = new ArrayList<>(); // Expected result + expectedModels.add(new SMSTypeModel()); // Populate as necessary + + when(smsMapper.smsTypeModelToSMSType(requestModel)).thenReturn(smsType); + when(smsTypeRepository.findSMSTypeByDeletedNotTrue(smsType.getServiceID())) + .thenReturn((ArrayList<SMSType>) smsTypes); + when(smsMapper.smsTypeToSMSTypeModel(smsTypes)).thenReturn(expectedModels); + + // When + String resultJson = smsService.getSMSTypes(requestModel); + + // Then + assertNotNull(resultJson); + // Assuming your JSON mapper works as expected, you might want to check for + // specific JSON output. + // For simplicity, here we'll just check that the result is not null or empty. + assertFalse(resultJson.isEmpty()); + + // Verify interactions + verify(smsMapper).smsTypeModelToSMSType(requestModel); + verify(smsTypeRepository).findSMSTypeByDeletedNotTrue(smsType.getServiceID()); + verify(smsMapper).smsTypeToSMSTypeModel(smsTypes); + } + +} diff --git a/src/test/java/com/iemr/common/service/snomedct/SnomedServiceImplTest.java b/src/test/java/com/iemr/common/service/snomedct/SnomedServiceImplTest.java new file mode 100644 index 00000000..b7ebda36 --- /dev/null +++ b/src/test/java/com/iemr/common/service/snomedct/SnomedServiceImplTest.java @@ -0,0 +1,104 @@ +package com.iemr.common.service.snomedct; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.iemr.common.data.snomedct.SCTDescription; +import com.iemr.common.repo.snomedct.SnomedRepository; + +import java.util.ArrayList; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class SnomedServiceImplTest { + + @Test + void testFindSnomedCTRecordFromTerm() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + SnomedRepository snomedRepository = mock(SnomedRepository.class); + when(snomedRepository.findSnomedCTRecordFromTerm(Mockito.<String>any())).thenReturn(new ArrayList<>()); + + SnomedServiceImpl snomedServiceImpl = new SnomedServiceImpl(); + snomedServiceImpl.setSnomedRepository(snomedRepository); + + // Act + SCTDescription actualFindSnomedCTRecordFromTermResult = snomedServiceImpl.findSnomedCTRecordFromTerm("Term"); + + // Assert + verify(snomedRepository).findSnomedCTRecordFromTerm(("Term")); + assertNull(actualFindSnomedCTRecordFromTermResult); + } + + @Test + void testFindSnomedCTRecordFromTerm2() { + // Diffblue Cover was unable to create a Spring-specific test for this Spring + // method. + + // Arrange + ArrayList<Object[]> objectArrayList = new ArrayList<>(); + objectArrayList.add(new Object[] { "42", "42" }); + SnomedRepository snomedRepository = mock(SnomedRepository.class); + when(snomedRepository.findSnomedCTRecordFromTerm(Mockito.<String>any())).thenReturn(objectArrayList); + + SnomedServiceImpl snomedServiceImpl = new SnomedServiceImpl(); + snomedServiceImpl.setSnomedRepository(snomedRepository); + + // Act + SCTDescription actualFindSnomedCTRecordFromTermResult = snomedServiceImpl.findSnomedCTRecordFromTerm("Term"); + + // Assert + verify(snomedRepository).findSnomedCTRecordFromTerm(("Term")); + assertEquals("42", actualFindSnomedCTRecordFromTermResult.getConceptID()); + assertEquals("42", actualFindSnomedCTRecordFromTermResult.getTerm()); + } + + @Test + void testFindSnomedCTRecordList() throws Exception { + assertThrows(Exception.class, () -> (new SnomedServiceImpl()).findSnomedCTRecordList(null)); + } + + @Test + void testFindSnomedCTRecordList2() throws Exception { + + // Arrange + SnomedServiceImpl snomedServiceImpl = new SnomedServiceImpl(); + + SCTDescription sctdescription = new SCTDescription(); + sctdescription.setActive("Active"); + sctdescription.setCaseSignificanceID("Case Significance ID"); + sctdescription.setConceptID("Concept ID"); + sctdescription.setSctDesID(1L); + sctdescription.setPageNo(null); + sctdescription.setTerm(null); + + // Act and Assert + assertThrows(Exception.class, () -> snomedServiceImpl.findSnomedCTRecordList(sctdescription)); + } + + @Test + void testFindSnomedCTRecordList3() throws Exception { + + // Arrange + SnomedServiceImpl snomedServiceImpl = new SnomedServiceImpl(); + + SCTDescription sctdescription = new SCTDescription(); + sctdescription.setActive("Active"); + sctdescription.setCaseSignificanceID("Case Significance ID"); + sctdescription.setConceptID("Concept ID"); + sctdescription.setSctDesID(1L); + sctdescription.setPageNo(null); + sctdescription.setTerm("foo"); + + // Act and Assert + assertThrows(Exception.class, () -> snomedServiceImpl.findSnomedCTRecordList(sctdescription)); + } +} diff --git a/src/test/java/com/iemr/common/service/uptsu/UptsuServiceImplTest.java b/src/test/java/com/iemr/common/service/uptsu/UptsuServiceImplTest.java new file mode 100644 index 00000000..c1d25c65 --- /dev/null +++ b/src/test/java/com/iemr/common/service/uptsu/UptsuServiceImplTest.java @@ -0,0 +1,110 @@ +package com.iemr.common.service.uptsu; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +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 java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.iemr.common.data.uptsu.FacilityMaster; +import com.iemr.common.data.uptsu.SmsRequestOBJ; +import com.iemr.common.repository.uptsu.FacilityMasterRepo; +import com.iemr.common.repository.uptsu.T_104AppointmentDetailsRepo; +import com.iemr.common.service.sms.SMSService; + +@ExtendWith(MockitoExtension.class) +class UptsuServiceImplTest { + + @InjectMocks + private UptsuServiceImpl uptsuService; + + @Mock + private FacilityMasterRepo facilityMasterRepo; + + @Mock + private T_104AppointmentDetailsRepo t_104AppointmentDetailsRepo; + @Mock + private SMSService smsService; + @Mock + private RestTemplate restTemplate; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testGetFacility() { + Integer providerServiceMapID = 1; + String blockname = "TestBlock"; + FacilityMaster facility1 = new FacilityMaster(); // Assuming FacilityMaster has a parameterless constructor + facility1.setId(1); // Assuming there's a method to set an ID or relevant fields + facility1.setBlockName(blockname); + + FacilityMaster facility2 = new FacilityMaster(); + facility2.setId(2); + facility2.setBlockName(blockname); + + List<FacilityMaster> expectedFacilities = Arrays.asList(facility1, facility2); + + when(facilityMasterRepo.findByProviderServiceMapIDAndBlockNameAndDeleted(providerServiceMapID, blockname, + false)).thenReturn(expectedFacilities); + + String result = uptsuService.getFacility(providerServiceMapID, blockname); + + assertEquals(new Gson().toJson(expectedFacilities), result, + "The returned JSON does not match the expected JSON."); + } + + @Test + void testCreateSmsGateway() throws Exception { + // Arrange + // Assuming we have some dummy data to pass to the method + String appointmentDate = "2024-03-17"; + String appointmentTime = "10:00 AM"; + String facilityPhoneNo = "1234567890"; + String choName = "Test CHO"; + String employeeCode = "EMP123"; + String beneficiaryName = "John Doe"; + Long beneficiaryId = 12345L; + String facilityName = "Test Facility"; + String hfrId = "HFR123"; + String benPhoneNo = "0987654321"; + Long benRegId = 67890L; + String Authorization = "Bearer someAuthToken"; + String createdBy = "TestUser"; + + // Act + uptsuService.createSmsGateway(appointmentDate, appointmentTime, facilityPhoneNo, choName, employeeCode, + beneficiaryName, beneficiaryId, facilityName, hfrId, benPhoneNo, benRegId, Authorization, createdBy); + + // Assert + // Verify that smsService.sendSMS was called twice (once for CHO and once for + // the beneficiary) + verify(smsService, times(2)).sendSMS(anyList(), eq(Authorization)); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/CommunityServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/CommunityServiceImplTest.java new file mode 100644 index 00000000..7c714834 --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/CommunityServiceImplTest.java @@ -0,0 +1,72 @@ +package com.iemr.common.service.userbeneficiarydata; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.userbeneficiarydata.Community; +import com.iemr.common.repo.snomedct.SnomedRepository; +import com.iemr.common.repository.beneficiary.CommunityRepository; +import com.iemr.common.repository.userbeneficiarydata.TitleRepository; +import com.iemr.common.service.snomedct.SnomedServiceImpl; +import com.iemr.common.service.userbeneficiarydata.CommunityServiceImpl; + +@ExtendWith(MockitoExtension.class) +public class CommunityServiceImplTest { + + @Mock + private CommunityRepository communityRepository; + + @InjectMocks + private CommunityServiceImpl communityService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + + @Test + void testGetActiveCommunities_WithValidData() { + // Setup mock data + Set<Object[]> mockData = new HashSet<>(); + mockData.add(new Object[] { 1, "Community A" }); + mockData.add(new Object[] { 2, "Community B" }); + + // Mocking repository call + when(communityRepository.findAciveCommunities()).thenReturn(mockData); + + // Call the method under test + List<Community> result = communityService.getActiveCommunities(); + + // Assertions + assertEquals(2, result.size()); + + } + + @Test + void testGetActiveCommunities_EmptySet() { + // Setup empty set for mocking + Set<Object[]> mockData = new HashSet<>(); + + // Mocking repository call + when(communityRepository.findAciveCommunities()).thenReturn(mockData); + + // Call the method under test + List<Community> result = communityService.getActiveCommunities(); + + // Assertions + assertEquals(0, result.size()); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/EducationServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/EducationServiceImplTest.java new file mode 100644 index 00000000..6c64311e --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/EducationServiceImplTest.java @@ -0,0 +1,62 @@ +package com.iemr.common.service.userbeneficiarydata; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.beneficiary.BeneficiaryEducation; +import com.iemr.common.repository.beneficiary.CommunityRepository; +import com.iemr.common.repository.beneficiary.EducationRepository; + +@ExtendWith(MockitoExtension.class) +public class EducationServiceImplTest { + + @Mock + private EducationRepository educationRepository; + + @InjectMocks + private EducationServiceImpl educationService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + + @Test + void testGetActiveEducations_WithValidData() { + Set<Object[]> mockData = new HashSet<>(); + mockData.add(new Object[] { 1L, "Primary" }); + mockData.add(new Object[] { 2L, "Secondary" }); + + when(educationRepository.findActiveEducations()).thenReturn(mockData); + + List<BeneficiaryEducation> result = educationService.getActiveEducations(); + + assertEquals(2, result.size()); + } + + @Test + void testGetActiveEducations_EmptySet() { + Set<Object[]> mockData = new HashSet<>(); + + when(educationRepository.findActiveEducations()).thenReturn(mockData); + + List<BeneficiaryEducation> result = educationService.getActiveEducations(); + + assertEquals(0, result.size()); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/GenderServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/GenderServiceImplTest.java new file mode 100644 index 00000000..d58ebea1 --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/GenderServiceImplTest.java @@ -0,0 +1,66 @@ +package com.iemr.common.service.userbeneficiarydata; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.userbeneficiarydata.Gender; +import com.iemr.common.repository.beneficiary.EducationRepository; +import com.iemr.common.repository.userbeneficiarydata.GenderRepository; + +@ExtendWith(MockitoExtension.class) +class GenderServiceImplTest { + + @Mock + private GenderRepository genderRepository; + + @InjectMocks + private GenderServiceImpl genderService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testGetActiveGenders_ReturnsNonEmptyList() { + // Mocking the repository response + Set<Object[]> mockedResponse = new HashSet<>(); + mockedResponse.add(new Object[] { 1, "Male" }); + mockedResponse.add(new Object[] { 2, "Female" }); + + when(genderRepository.findAciveGenders()).thenReturn(mockedResponse); + + // Calling the method under test + List<Gender> activeGenders = genderService.getActiveGenders(); + + // Assertions + assertEquals(2, activeGenders.size(), "Should return a list with two genders"); + + } + + @Test + void testGetActiveGenders_ReturnsEmptyListWhenRepositoryIsEmpty() { + // Mocking an empty repository response + when(genderRepository.findAciveGenders()).thenReturn(new HashSet<>()); + + // Calling the method under test + List<Gender> activeGenders = genderService.getActiveGenders(); + + // Assertions + assertEquals(0, activeGenders.size(), "Should return an empty list"); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/LanguageServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/LanguageServiceImplTest.java new file mode 100644 index 00000000..5da019e7 --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/LanguageServiceImplTest.java @@ -0,0 +1,66 @@ +package com.iemr.common.service.userbeneficiarydata; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.userbeneficiarydata.Language; +import com.iemr.common.repository.userbeneficiarydata.LanguageRepository; + +@ExtendWith(MockitoExtension.class) +class LanguageServiceImplTest { + + @Mock + private LanguageRepository languageRepository; + + @InjectMocks + private LanguageServiceImpl languageService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + + @Test + void testGetActiveLanguages_ReturnsNonEmptyList() { + // Mocking the repository response + Set<Object[]> mockedResponse = new HashSet<>(); + mockedResponse.add(new Object[] { 1, "English" }); + mockedResponse.add(new Object[] { 2, "Spanish" }); + + when(languageRepository.findAciveLanguages()).thenReturn(mockedResponse); + + // Calling the method under test + List<Language> activeLanguages = languageService.getActiveLanguages(); + + // Assertions + assertEquals(2, activeLanguages.size(), "Should return a list with two languages"); + // Additional checks can be added to verify the contents of the list + } + + @Test + void testGetActiveLanguages_ReturnsEmptyListWhenRepositoryIsEmpty() { + // Mocking an empty repository response + when(languageRepository.findAciveLanguages()).thenReturn(new HashSet<>()); + + // Calling the method under test + List<Language> activeLanguages = languageService.getActiveLanguages(); + + // Assertions + assertEquals(0, activeLanguages.size(), "Should return an empty list"); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/MaritalStatusServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/MaritalStatusServiceImplTest.java new file mode 100644 index 00000000..b714e26a --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/MaritalStatusServiceImplTest.java @@ -0,0 +1,66 @@ +package com.iemr.common.service.userbeneficiarydata; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.iemr.common.data.userbeneficiarydata.MaritalStatus; +import com.iemr.common.repository.userbeneficiarydata.GenderRepository; +import com.iemr.common.repository.userbeneficiarydata.MaritalStatusRepository; +@ExtendWith(MockitoExtension.class) +class MaritalStatusServiceImplTest { + + @Mock + private MaritalStatusRepository maritalStatusRepository; + + @InjectMocks + private MaritalStatusServiceImpl maritalStatusService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + + @Test + void testGetActiveMaritalStatus_ReturnsNonEmptyList() { + // Mocking the repository response + Set<Object[]> mockedResponse = new HashSet<>(); + mockedResponse.add(new Object[] { 1, "Single" }); + mockedResponse.add(new Object[] { 2, "Married" }); + + when(maritalStatusRepository.findAciveMaritalStatus()).thenReturn(mockedResponse); + + // Calling the method under test + List<MaritalStatus> activeMaritalStatuses = maritalStatusService.getActiveMaritalStatus(); + + // Assertions + assertEquals(2, activeMaritalStatuses.size(), "Should return a list with two marital statuses"); + } + + @Test + void testGetActiveMaritalStatus_ReturnsEmptyListWhenRepositoryIsEmpty() { + // Mocking an empty repository response + when(maritalStatusRepository.findAciveMaritalStatus()).thenReturn(new HashSet<>()); + + // Calling the method under test + List<MaritalStatus> activeMaritalStatuses = maritalStatusService.getActiveMaritalStatus(); + + // Assertions + assertEquals(0, activeMaritalStatuses.size(), "Should return an empty list"); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/RelegionServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/RelegionServiceImplTest.java new file mode 100644 index 00000000..06bb6c32 --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/RelegionServiceImplTest.java @@ -0,0 +1,58 @@ +package com.iemr.common.service.userbeneficiarydata; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import com.iemr.common.data.userbeneficiarydata.Religion; +import com.iemr.common.repository.userbeneficiarydata.MaritalStatusRepository; +import com.iemr.common.repository.userbeneficiarydata.ReligionRepository; + +class RelegionServiceImplTest { + @Mock + private ReligionRepository religionRepository; + + @InjectMocks + private RelegionServiceImpl religionService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void getActiveReligionsReturnsCorrectData() { + // Setup our mocked repository + Object[] religionData1 = { 1, "Hinduism", "Active" }; + Object[] religionData2 = { 2, "Islam", "Active" }; + List<Object[]> mockData = Arrays.asList(religionData1, religionData2); + when(religionRepository.getActiveReligions()).thenReturn(mockData); + + // Execute the service call + List<Religion> result = religionService.getActiveReligions(); + + // Validate the results + assertNotNull(result, "The result should not be null"); + assertEquals(2, result.size(), "There should be two active religions in the result"); + + // Validate the content of the result + assertEquals(1, result.get(0).getReligionID()); + assertEquals("Hinduism", result.get(0).getReligionType()); + assertEquals("Active", result.get(0).getReligionDesc()); + + assertEquals(2, result.get(1).getReligionID()); + assertEquals("Islam", result.get(1).getReligionType()); + assertEquals("Active", result.get(1).getReligionDesc()); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/StatusServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/StatusServiceImplTest.java new file mode 100644 index 00000000..0c9eca18 --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/StatusServiceImplTest.java @@ -0,0 +1,76 @@ +package com.iemr.common.service.userbeneficiarydata; + +import static org.mockito.Mockito.*; + +import com.iemr.common.data.userbeneficiarydata.Status; +import com.iemr.common.repository.userbeneficiarydata.MaritalStatusRepository; +import com.iemr.common.repository.userbeneficiarydata.StatusRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(MockitoExtension.class) +class StatusServiceImplTest { + + @Mock + private StatusRepository statusRepository; + + @InjectMocks + private StatusServiceImpl statusService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void setTitleServiceImpl() { + // Arrange and Act + (new StatusServiceImpl()).setTitleServiceImpl(mock(StatusRepository.class)); + } + + @Test + void getActiveStatus_whenStatusFound() { + // Setup + Set<Object[]> mockResponse = new HashSet<>(); + mockResponse.add(new Object[] { 1, "Active" }); + when(statusRepository.findAciveStatus()).thenReturn(mockResponse); + + // Execution + List<Status> result = statusService.getActiveStatus(); + + // Verification + assertNotNull(result); + assertFalse(result.isEmpty()); + assertEquals(1, result.size()); + assertEquals("Active", result.get(0).getStatus()); + + verify(statusRepository).findAciveStatus(); + } + + @Test + void getActiveStatus_whenStatusNotFound() { + // Setup + when(statusRepository.findAciveStatus()).thenReturn(new HashSet<>()); + + // Execution + List<Status> result = statusService.getActiveStatus(); + + // Verification + assertNotNull(result); + assertTrue(result.isEmpty()); + + verify(statusRepository).findAciveStatus(); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/TitleServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/TitleServiceImplTest.java new file mode 100644 index 00000000..d9c06840 --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/TitleServiceImplTest.java @@ -0,0 +1,72 @@ +package com.iemr.common.service.userbeneficiarydata; + +import com.iemr.common.data.userbeneficiarydata.Title; +import com.iemr.common.repository.userbeneficiarydata.StatusRepository; +import com.iemr.common.repository.userbeneficiarydata.TitleRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class TitleServiceImplTest { + + @Mock + private TitleRepository titleRepository; + + @InjectMocks + private TitleServiceImpl titleService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void getActiveTitles_whenTitlesFound() { + // Setup + Set<Object[]> mockResponse = new HashSet<>(); + mockResponse.add(new Object[] { 1, "Dr.", "A title description" }); + when(titleRepository.findAciveTitles()).thenReturn(mockResponse); + + // Execution + List<Title> result = titleService.getActiveTitles(); + + // Verification + assertNotNull(result); + assertFalse(result.isEmpty()); + assertEquals(1, result.size()); + + // Verify the content based on getTitle method's behavior + Title expectedTitle = new Title().getTitle(1, "Dr."); // This should match the behavior of your getTitle method + assertEquals(expectedTitle.getTitleID(), result.get(0).getTitleID()); + assertEquals(expectedTitle.getTitleName(), result.get(0).getTitleName()); + + verify(titleRepository).findAciveTitles(); + } + + @Test + void getActiveTitles_whenNoTitlesFound() { + // Setup + when(titleRepository.findAciveTitles()).thenReturn(new HashSet<>()); + + // Execution + List<Title> result = titleService.getActiveTitles(); + + // Verification + assertNotNull(result); + assertTrue(result.isEmpty()); + + verify(titleRepository).findAciveTitles(); + } + +} diff --git a/src/test/java/com/iemr/common/service/userbeneficiarydata/UserBeneficiaryDataServiceImplTest.java b/src/test/java/com/iemr/common/service/userbeneficiarydata/UserBeneficiaryDataServiceImplTest.java new file mode 100644 index 00000000..b7deb512 --- /dev/null +++ b/src/test/java/com/iemr/common/service/userbeneficiarydata/UserBeneficiaryDataServiceImplTest.java @@ -0,0 +1,64 @@ +package com.iemr.common.service.userbeneficiarydata; + +import com.iemr.common.data.userbeneficiarydata.Gender; +import com.iemr.common.repository.userbeneficiarydata.UserBeneficiaryDataRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; +@ExtendWith(MockitoExtension.class) +public class UserBeneficiaryDataServiceImplTest { + + @Mock + private UserBeneficiaryDataRepository userBeneficiaryDataRepository; + + @InjectMocks + private UserBeneficiaryDataServiceImpl userBeneficiaryDataService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void getActiveGender_WhenFound() { + // Arrange + Set<Object[]> mockResponse = new HashSet<>(); + mockResponse.add(new Object[] { 1, "Male" }); + mockResponse.add(new Object[] { 2, "Female" }); + when(userBeneficiaryDataRepository.findActiveGenders()).thenReturn(mockResponse); + + // Act + List<Gender> result = userBeneficiaryDataService.getActiveGender(); + + // Assert + assertEquals(2, result.size()); + assertTrue(result.stream().anyMatch(g -> g.getGenderName().equals("Male") && g.getGenderID().equals(1))); + assertTrue(result.stream().anyMatch(g -> g.getGenderName().equals("Female") && g.getGenderID().equals(2))); + } + + @Test + void getActiveGender_WhenNoneFound() { + // Arrange + Set<Object[]> mockResponse = new HashSet<>(); + when(userBeneficiaryDataRepository.findActiveGenders()).thenReturn(mockResponse); + + // Act + List<Gender> result = userBeneficiaryDataService.getActiveGender(); + + // Assert + assertTrue(result.isEmpty()); + } + +} diff --git a/src/test/java/com/iemr/common/service/users/EmployeeSignatureServiceImplTest.java b/src/test/java/com/iemr/common/service/users/EmployeeSignatureServiceImplTest.java new file mode 100644 index 00000000..00270cdc --- /dev/null +++ b/src/test/java/com/iemr/common/service/users/EmployeeSignatureServiceImplTest.java @@ -0,0 +1,82 @@ +package com.iemr.common.service.users; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; + +import com.iemr.common.data.users.EmployeeSignature; +import com.iemr.common.repository.users.EmployeeSignatureRepo; +import com.iemr.common.service.users.EmployeeSignatureServiceImpl; +@ExtendWith(MockitoExtension.class) +public class EmployeeSignatureServiceImplTest { + + @Mock + private EmployeeSignatureRepo employeeSignatureRepo; + + @InjectMocks + private EmployeeSignatureServiceImpl service; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testFetchSignature_ExistingUser() { + Long userSignID = 1L; + EmployeeSignature mockSignature = new EmployeeSignature(); + // Assuming EmployeeSignature has a setUserID method or similar to set the ID. + mockSignature.setUserID(userSignID); // Setup mock data as per your class structure + + when(employeeSignatureRepo.findOneByUserID(userSignID)).thenReturn(mockSignature); + + EmployeeSignature result = service.fetchSignature(userSignID); + + assertNotNull(result); + assertEquals(userSignID, result.getUserID()); + verify(employeeSignatureRepo).findOneByUserID(userSignID); + } + + @Test + void testFetchSignature_NonExistingUser() { + Long userSignID = 99L; + + when(employeeSignatureRepo.findOneByUserID(userSignID)).thenReturn(null); + + EmployeeSignature result = service.fetchSignature(userSignID); + + assertNull(result); + verify(employeeSignatureRepo).findOneByUserID(userSignID); + } + + @Test + void testExistSignature_True() { + Long userID = 1L; + + when(employeeSignatureRepo.countByUserIDAndSignatureNotNull(userID)).thenReturn(1L); + + Boolean exists = service.existSignature(userID); + + assertTrue(exists); + verify(employeeSignatureRepo).countByUserIDAndSignatureNotNull(userID); + } + + @Test + void testExistSignature_False() { + Long userID = 99L; + + when(employeeSignatureRepo.countByUserIDAndSignatureNotNull(userID)).thenReturn(0L); + + Boolean exists = service.existSignature(userID); + + assertFalse(exists); + verify(employeeSignatureRepo).countByUserIDAndSignatureNotNull(userID); + } +} diff --git a/src/test/java/com/iemr/common/users/IEMRAdminControllerTest.java b/src/test/java/com/iemr/common/users/IEMRAdminControllerTest.java index 2b4eb782..8dea35e2 100644 --- a/src/test/java/com/iemr/common/users/IEMRAdminControllerTest.java +++ b/src/test/java/com/iemr/common/users/IEMRAdminControllerTest.java @@ -24,7 +24,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.fasterxml.jackson.core.JsonProcessingException; @@ -33,10 +32,7 @@ import com.iemr.common.service.users.IEMRAdminUserServiceImpl; import com.iemr.common.utils.exception.IEMRException; -//@RunWith(SpringJUnit4ClassRunner.class) -//@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class IEMRAdminControllerTest -{ +public class IEMRAdminControllerTest { private static IEMRAdminUserService testService; @@ -55,11 +51,9 @@ public class IEMRAdminControllerTest private static final String OUTPUT_ROLES_BY_PROVIDER_ID_FAILURE_1 = ""; // @Before - public void initializeTest() throws JsonMappingException, JsonProcessingException - { + public void initializeTest() throws JsonMappingException, JsonProcessingException { testService = mock(IEMRAdminUserServiceImpl.class); - try - { + try { /* Success mocks */ when(testService.getRolesByProviderID(INPUT_ROLES_BY_PROVIDER_ID_SUCCESS_1)) .thenReturn(OUTPUT_ROLES_BY_PROVIDER_ID_SUCCESS_1); @@ -69,26 +63,8 @@ public void initializeTest() throws JsonMappingException, JsonProcessingExceptio /* Failure mocks */ when(testService.getRolesByProviderID(INPUT_ROLES_BY_PROVIDER_ID_FAILURE_1)) .thenReturn(OUTPUT_ROLES_BY_PROVIDER_ID_FAILURE_1); - } catch (IEMRException e) - { + } catch (IEMRException e) { e.printStackTrace(); } } } - -// @Test -// public void test001GetRolesByProviderIDSuccess() -// { -// try -// { -// assertTrue(testService.getRolesByProviderID(INPUT_ROLES_BY_PROVIDER_ID_SUCCESS_1) -// .equals(OUTPUT_ROLES_BY_PROVIDER_ID_SUCCESS_1)); -// assertTrue(testService.getRolesByProviderID(INPUT_ROLES_BY_PROVIDER_ID_SUCCESS_2) -// .equals(OUTPUT_ROLES_BY_PROVIDER_ID_SUCCESS_2)); -// } catch (IEMRException e) -// { -// e.printStackTrace(); -// } -// } -// -//}