Java tutorial
package com.ccserver.digital.controller; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.net.URISyntaxException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.validation.BindingResult; import com.ccserver.digital.common.Constants; import com.ccserver.digital.domain.SelectionList; import com.ccserver.digital.domain.base.ErrorObject; import com.ccserver.digital.domain.type.DocumentTemplate; import com.ccserver.digital.domain.type.Gender; import com.ccserver.digital.domain.type.TypeOfEmployment; import com.ccserver.digital.dto.AddressDTO; import com.ccserver.digital.dto.BaseProvinceDTO; import com.ccserver.digital.dto.CompanyDTO; import com.ccserver.digital.dto.CountryDTO; import com.ccserver.digital.dto.CreditCardApplicationDTO; import com.ccserver.digital.dto.CreditCardApplicationDocumentDTO; import com.ccserver.digital.dto.CreditCardApplicationDocumentThumbNailDTO; import com.ccserver.digital.dto.DistrictDTO; import com.ccserver.digital.dto.DocumentSubTypeDTO; import com.ccserver.digital.dto.DocumentTypeDTO; import com.ccserver.digital.dto.PhoneDTO; import com.ccserver.digital.dto.SelectionListDTO; import com.ccserver.digital.service.CreditCardApplicationDocumentService; import com.ccserver.digital.service.CreditCardApplicationService; import com.ccserver.digital.service.UtilService; import com.ccserver.digital.validator.CreditCardApplicationDocumentValidator; @RunWith(SpringRunner.class) public class CreditCardApplicationDocumentControllerTest { @InjectMocks private CreditCardApplicationDocumentController mockDocController; @Mock private CreditCardApplicationDocumentService mockDocService; @Mock private CreditCardApplicationService ccAppService; @Mock private UtilService utilService; @Mock private CreditCardApplicationDocumentValidator validator; @Mock private BindingResult errors; @Mock private HttpServletRequest request; @Test public void save() throws IOException { File ifile = new File("./src/main/resources/sample"); Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf"); byte[] idDocByteArray = Files.readAllBytes(idDocPath); MockMultipartFile idDocMultipartFile = new MockMultipartFile("IdDoc", "IdDoc.pdf", "application/pdf", idDocByteArray); ResponseEntity<?> fileUploadResponse = mockDocController.saveAll( new MockMultipartFile[] { idDocMultipartFile }, new String[] { "front" }, Long.valueOf(1), Long.valueOf(1), request); Assert.assertNotNull(fileUploadResponse); } @Test public void modifySubmittedDocumentTest() throws IOException { // Arrange long id = 1l; long docId = 1l; CreditCardApplicationDocumentDTO doc = new CreditCardApplicationDocumentDTO(); doc.setId(docId); File ifile = new File("./src/main/resources/sample"); Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf"); byte[] idDocByteArray = Files.readAllBytes(idDocPath); MockMultipartFile idDocMultipartFile = new MockMultipartFile("IdDoc", "IdDoc.pdf", "application/pdf", idDocByteArray); Mockito.when(ccAppService.isSubmittedDocument(id)).thenReturn(true); Mockito.when(mockDocService.documentIsBelongToApp(id, docId)).thenReturn(true); // Act ResponseEntity<?> response = mockDocController.saveAll(new MockMultipartFile[] { idDocMultipartFile }, null, id, docId, request); // Assert Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertEquals(Constants.MODIFYING_SUBMITTED_DOCUMENT, ((ErrorObject) response.getBody()).getId()); } @Test public void downloadDocumentAppIdMockTest() throws IOException, URISyntaxException { File ifile = new File("./src/main/resources/sample"); Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf"); byte[] idDocByteArray = Files.readAllBytes(idDocPath); CreditCardApplicationDocumentDTO ccAppDocDTO = new CreditCardApplicationDocumentDTO(); ccAppDocDTO.setId(1L); ccAppDocDTO.setDocument(idDocByteArray); ccAppDocDTO.setFileName("name"); List<CreditCardApplicationDocumentDTO> ccAppDocDTOs = new ArrayList<CreditCardApplicationDocumentDTO>(); ccAppDocDTOs.add(ccAppDocDTO); CreditCardApplicationDTO ccAppDTO = getCreditCardApplicationDTOMock(1L); Mockito.when(mockDocService.getDocumentsByApplicationId(1L)).thenReturn(ccAppDocDTOs); ResponseEntity<?> response = mockDocController.downloadDocumentByAppId(1L); List<CreditCardApplicationDocumentDTO> result = (List<CreditCardApplicationDocumentDTO>) response.getBody(); Assert.assertEquals(result.size(), 1); } @Test public void downloadDocumentWithWrongId() { // when ResponseEntity<?> response = mockDocController.downloadDocumentByAppId(0L); // then Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertEquals(Constants.APPLICATION_ID_REQUIRED, ((ErrorObject) response.getBody()).getId()); } @Test public void downloadDocumentWithNullId() { // when ResponseEntity<?> response = mockDocController.downloadDocumentByAppId(null); // then Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertEquals(Constants.APPLICATION_ID_REQUIRED, ((ErrorObject) response.getBody()).getId()); } @Test public void downloadDocumentWithEmptyReturnedObject() { Mockito.when(mockDocService.getDocumentsByApplicationId(1L)) .thenReturn(new ArrayList<CreditCardApplicationDocumentDTO>()); ResponseEntity<?> response = mockDocController.downloadDocumentByAppId(1L); // assert Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); ArrayList<CreditCardApplicationDocumentDTO> docs = (ArrayList<CreditCardApplicationDocumentDTO>) response .getBody(); Assert.assertTrue(docs.isEmpty()); } @Test public void downloadDocumentByIdDocMockTest() throws IOException, URISyntaxException { File ifile = new File("./src/main/resources/sample"); Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf"); byte[] idDocByteArray = Files.readAllBytes(idDocPath); CreditCardApplicationDocumentThumbNailDTO CCAppDocThumbNailDTO = new CreditCardApplicationDocumentThumbNailDTO(); CCAppDocThumbNailDTO.setId(1L); CCAppDocThumbNailDTO.setDocument(idDocByteArray); CCAppDocThumbNailDTO.setThumbNail(idDocByteArray); CCAppDocThumbNailDTO.setFileName("name"); Mockito.when(mockDocService.findByCreditCardApplicationDocumentId(1L)).thenReturn(CCAppDocThumbNailDTO); Mockito.when(mockDocService.documentIsBelongToApp(1L, 1L)).thenReturn(true); ResponseEntity<?> response = mockDocController.downloadDocumentByDocId(1L, 1L); CreditCardApplicationDocumentThumbNailDTO result = (CreditCardApplicationDocumentThumbNailDTO) response .getBody(); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertTrue(result.getId() > 0); } @Test public void downloadDocumentByIdDocWithWrongId() { // when ResponseEntity<?> response = mockDocController.downloadDocumentByDocId(0L, 0L); // then Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertEquals(Constants.APPLICATION_ID_REQUIRED, ((ErrorObject) response.getBody()).getId()); } @Test public void downloadDocumentByIdDocWithNullId() { // when ResponseEntity<?> response = mockDocController.downloadDocumentByDocId(null, null); // then Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertEquals(Constants.APPLICATION_ID_REQUIRED, ((ErrorObject) response.getBody()).getId()); } CreditCardApplicationDTO getCreditCardApplicationDTOMock(long id) { CreditCardApplicationDTO creditCardApplicationDTOMock = getCreditCardApplicationDTO(); creditCardApplicationDTOMock.setId(id); creditCardApplicationDTOMock.getMobile().setId(id); creditCardApplicationDTOMock.getBusinessPhone().setId(id); creditCardApplicationDTOMock.getBusinessTelephone().setId(id); creditCardApplicationDTOMock.getSecurityQuestion().setId(id); creditCardApplicationDTOMock.getPhoneOfReference().setId(id); return creditCardApplicationDTOMock; } private CreditCardApplicationDTO getCreditCardApplicationDTO() { CreditCardApplicationDTO creditCardApplicationDTO = new CreditCardApplicationDTO(); // ----- cardType // ----- DoB creditCardApplicationDTO.setDob(LocalDateTime.now()); // ----- Name creditCardApplicationDTO.setFirstName("LE"); creditCardApplicationDTO.setMiddleName("Hong"); creditCardApplicationDTO.setLastName("Thanh"); // ----- gender creditCardApplicationDTO.setGender(Gender.Male); // ----- Moblie PhoneDTO moblie = new PhoneDTO(); moblie.setCountryCode("084"); moblie.setPhoneNumber("0985481179"); creditCardApplicationDTO.setMobile(moblie); // ----- phoneBusiness PhoneDTO phoneBusiness = new PhoneDTO(); phoneBusiness.setCountryCode("084"); phoneBusiness.setPhoneNumber("0985481179"); creditCardApplicationDTO.setBusinessPhone(phoneBusiness); // ----- email creditCardApplicationDTO.setEmail("letuanthuongtin@gmail.com"); // ----- passportNumber creditCardApplicationDTO.setPassportNumber("123456789"); // ----- dateOfIssue creditCardApplicationDTO.setDateOfIssue(LocalDateTime.now()); // ----- placeOfIssue SelectionList selectionListDTO = new SelectionList(); selectionListDTO.setCategory("plauceOfise"); selectionListDTO.setCode("11"); creditCardApplicationDTO.setPlaceOfIssue(selectionListDTO); // ----- citizenship CountryDTO citizenship = new CountryDTO(); citizenship.setId(1L); citizenship.setCode("VN"); citizenship.setVi("Viet Nam"); citizenship.setEn("VietNam"); creditCardApplicationDTO.setCitizenship(citizenship); // ----- haveGreenCard creditCardApplicationDTO.setHaveGreenCard(true); // ----- isUSResident creditCardApplicationDTO.setUSResident(true); // ----- education // creditCardApplicationDTO.setEducation(EducationQualification.HighShool); // ----- maritalStatus // creditCardApplicationDTO.setMaritalStatus(MaritalStatus.Single); // ----- numberOfChildren creditCardApplicationDTO.setNumberOfChildren(4); // ----- permanent address--- // TODO: create province and district for integration test AddressDTO permanentAddress = new AddressDTO(); BaseProvinceDTO province = new BaseProvinceDTO(); province.setName("Ha Noi"); province.setId(1L); DistrictDTO districtDTO1 = new DistrictDTO(); districtDTO1.setName("Hai Ba Trung"); districtDTO1.setId(1L); permanentAddress.setDistrict(districtDTO1); permanentAddress.setProvince(province); permanentAddress.setStreet("LE Thanh NGhi"); permanentAddress.setAddressDetails("So Nha 18"); creditCardApplicationDTO.setPermanentAddress(permanentAddress); // ----- currentIsPermanent creditCardApplicationDTO.setCurrentIsPermanent(true); // ----- currentAddress creditCardApplicationDTO.setCurrentAddress(permanentAddress); // ----- typeOfEmployement creditCardApplicationDTO.setTypeOfEmployement(TypeOfEmployment.Business); // ----- licenseNumber creditCardApplicationDTO.setLicenseNumber("12345"); // ----- businessStartDate creditCardApplicationDTO.setBusinessStartDate(LocalDateTime.now()); // ----- businessTelephone PhoneDTO businessTelephone = new PhoneDTO(); businessTelephone.setCountryCode("084"); businessTelephone.setPhoneNumber("0985481179"); businessTelephone.setExt("01"); creditCardApplicationDTO.setBusinessTelephone(businessTelephone); // ----- businessAddress creditCardApplicationDTO.setBusinessAddress(permanentAddress); // ----- nameOfEmployer CompanyDTO companyDTO = new CompanyDTO(); companyDTO.setCode("111"); creditCardApplicationDTO.setNameOfEmployer(companyDTO); // ----- occupation //creditCardApplicationDTO.setOccupation("Engineer"); // ----- industry // creditCardApplicationDTO.setIndustry("finance"); // ----- yearsOfWorking creditCardApplicationDTO.setYearsOfWorking(1); // ----- monthsOfWorking creditCardApplicationDTO.setMonthsOfWorking(8); // ----- employerAddress creditCardApplicationDTO.setEmployerAddress(permanentAddress); // ----- monthlyIncome creditCardApplicationDTO.setMonthlyIncome(new BigDecimal("10")); // ----- monthlyExpenses creditCardApplicationDTO.setMonthlyExpenses(new BigDecimal("5")); // ----- securityQuestion SelectionListDTO securityQuestion = new SelectionListDTO(); securityQuestion.setId(3L); creditCardApplicationDTO.setSecurityQuestion(securityQuestion); // ----- securityAnswer creditCardApplicationDTO.setSecurityAnswer("Thanh"); // ----- referenceName creditCardApplicationDTO.setReferenceName("LE Tuan"); // ----- relationshipReference SelectionListDTO relationship = new SelectionListDTO(); relationship.setId(3L); creditCardApplicationDTO.setRelationshipReference(relationship); // ----- phoneOfReference creditCardApplicationDTO.setPhoneOfReference(moblie); // ----- branchDelivery // creditCardApplicationDTO.setDeliveryCard("Branch 1"); // ----- isSecondaryCard creditCardApplicationDTO.setSecondaryCard(true); // ----- isAccurateCommit creditCardApplicationDTO.setAccurateCommit(true); // ----- agreeTermsConditions creditCardApplicationDTO.setAgreeTermsConditions(true); return creditCardApplicationDTO; } @Test public void deleteDocumentTest() { // Arrange long id = 1l; long docId = 1l; CreditCardApplicationDocumentDTO doc = new CreditCardApplicationDocumentDTO(); doc.setId(docId); Mockito.when(mockDocService.delete(id)).thenReturn(doc); Mockito.when(mockDocService.documentIsBelongToApp(1L, 1L)).thenReturn(true); // Act ResponseEntity<?> response = mockDocController.deleteDocument(id, docId); // Assert Mockito.verify(this.mockDocService, Mockito.times(1)).delete(id); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); } @Test public void deleteDocumentWithZeroIdTest() { // Arrange long id = 1l; long docId = 0l; CreditCardApplicationDocumentDTO doc = new CreditCardApplicationDocumentDTO(); doc.setId(docId); Mockito.when(mockDocService.delete(id)).thenReturn(doc); // Act ResponseEntity<?> response = mockDocController.deleteDocument(id, docId); // Assert Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); } @Test public void deleteSubmittedDocumentTest() { // Arrange long id = 1l; long docId = 1l; CreditCardApplicationDocumentDTO doc = new CreditCardApplicationDocumentDTO(); doc.setId(docId); Mockito.when(ccAppService.isSubmittedDocument(id)).thenReturn(true); Mockito.when(mockDocService.documentIsBelongToApp(id, docId)).thenReturn(true); // Act ResponseEntity<?> response = mockDocController.deleteDocument(id, docId); // Assert Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertEquals(Constants.MODIFYING_SUBMITTED_DOCUMENT, ((ErrorObject) response.getBody()).getId()); } @Test public void getDocumentTypesTest() { // Arrange List<DocumentTypeDTO> docTypeDTOs = new ArrayList<DocumentTypeDTO>(); Set<DocumentSubTypeDTO> subTypeDTOs = new HashSet<DocumentSubTypeDTO>(); DocumentSubTypeDTO subType = new DocumentSubTypeDTO(); subType.setId(1l); subType.setTemplate(DocumentTemplate.MULTI_PAGES); subType.setNames(new HashMap<String, String>()); subTypeDTOs.add(subType); DocumentTypeDTO docTypeDTO = new DocumentTypeDTO(); docTypeDTO.setIcon("icon1"); docTypeDTO.setId(1l); docTypeDTO.setSubTypes(subTypeDTOs); docTypeDTO.setNames(new HashMap<String, String>()); docTypeDTO.setTitles(new HashMap<String, String>()); docTypeDTOs.add(docTypeDTO); Mockito.when(utilService.getDocumentTypes(1l)).thenReturn(docTypeDTOs); // Act ResponseEntity<?> docTypes = mockDocController.getDocumentTypes(1l); // Assert Assert.assertEquals(HttpStatus.OK, docTypes.getStatusCode()); List<DocumentTypeDTO> list = (List<DocumentTypeDTO>) docTypes.getBody(); Assert.assertEquals("icon1", list.get(0).getIcon()); Assert.assertEquals(docTypeDTOs, list); } }