method2testcases
stringlengths 118
3.08k
|
---|
### Question:
ComplaintStatusSearchCriteria { public void validate() { if (isCodeAbsent() || isRolesAbsent()) { throw new InvalidComplaintStatusSearchException(this); } } void validate(); boolean isCodeAbsent(); boolean isRolesAbsent(); }### Answer:
@Test(expected = InvalidComplaintStatusSearchException.class) public void test_should_fail_validation_when_name_is_empty() { ComplaintStatusSearchCriteria complaintStatusSearchCriteria = new ComplaintStatusSearchCriteria("", asList(1L, 2L), "default"); complaintStatusSearchCriteria.validate(); }
@Test(expected = InvalidComplaintStatusSearchException.class) public void test_should_fail_validation_when_name_is_null() { ComplaintStatusSearchCriteria complaintStatusSearchCriteria = new ComplaintStatusSearchCriteria(null, asList(1L, 2L), "default"); complaintStatusSearchCriteria.validate(); }
@Test(expected = InvalidComplaintStatusSearchException.class) public void test_should_fail_validation_when_roles_is_empty() { ComplaintStatusSearchCriteria complaintStatusSearchCriteria = new ComplaintStatusSearchCriteria("NAME", Collections.emptyList(), "default"); complaintStatusSearchCriteria.validate(); }
@Test(expected = InvalidComplaintStatusSearchException.class) public void test_should_fail_validation_when_roles_is_null() { ComplaintStatusSearchCriteria complaintStatusSearchCriteria = new ComplaintStatusSearchCriteria("NAME", null, "default"); complaintStatusSearchCriteria.validate(); }
|
### Question:
StateService { public State getStateByIdAndTenantId(final Long id, final String tenantId) { return stateRepository.findByIdAndTenantId(id,tenantId); } @Autowired StateService(final StateRepository stateRepository); boolean isPositionUnderWorkflow(final Long posId, final Date givenDate); List<String> getAssignedWorkflowTypeNames(List<Long> ownerIds,List<String> enabledTypes); State getStateByIdAndTenantId(final Long id, final String tenantId); @Transactional State create(final State state); @Transactional State update(final State state); }### Answer:
@Test public void testShouldReturnStateWhenStateIdIsSpecified() { final State expectedState = new State(); expectedState.setId(1L); when(stateRepository.findByIdAndTenantId(1L,"tenantId")).thenReturn(expectedState); final State actualState = stateService.getStateByIdAndTenantId(1L,"tenantId"); assertEquals(1, actualState.getId().intValue()); assertEquals(expectedState, actualState); }
|
### Question:
StateService { @Transactional public State create(final State state) { return stateRepository.save(state); } @Autowired StateService(final StateRepository stateRepository); boolean isPositionUnderWorkflow(final Long posId, final Date givenDate); List<String> getAssignedWorkflowTypeNames(List<Long> ownerIds,List<String> enabledTypes); State getStateByIdAndTenantId(final Long id, final String tenantId); @Transactional State create(final State state); @Transactional State update(final State state); }### Answer:
@Test public void testShouldCreateStateWhenStateIsProvided() { final State state = getState(); final State expectedState = new State(); when(stateRepository.save(state)).thenReturn(expectedState); final State actualState = stateService.create(state); assertEquals(expectedState, actualState); }
|
### Question:
StateService { @Transactional public State update(final State state) { return stateRepository.save(state); } @Autowired StateService(final StateRepository stateRepository); boolean isPositionUnderWorkflow(final Long posId, final Date givenDate); List<String> getAssignedWorkflowTypeNames(List<Long> ownerIds,List<String> enabledTypes); State getStateByIdAndTenantId(final Long id, final String tenantId); @Transactional State create(final State state); @Transactional State update(final State state); }### Answer:
@Test public void testShouldUpdateStateWhenStateIsProvided() { final State state = getState(); final State expectedState = new State(); when(stateRepository.save(state)).thenReturn(expectedState); final State actualState = stateService.update(state); assertEquals(expectedState, actualState); }
|
### Question:
StateService { public List<String> getAssignedWorkflowTypeNames(List<Long> ownerIds,List<String> enabledTypes) { return stateRepository.findAllTypeByOwnerAndStatus(ownerIds,enabledTypes); } @Autowired StateService(final StateRepository stateRepository); boolean isPositionUnderWorkflow(final Long posId, final Date givenDate); List<String> getAssignedWorkflowTypeNames(List<Long> ownerIds,List<String> enabledTypes); State getStateByIdAndTenantId(final Long id, final String tenantId); @Transactional State create(final State state); @Transactional State update(final State state); }### Answer:
@Test public void testShouldGetAssignedWorkFlowTypeNamesWhenWorkFlowTypeAndOwnerIdIsProvided() { final List<Long> ownerIds = new ArrayList<>(); ownerIds.add(34L); ownerIds.add(35L); final List<String> types = new ArrayList<>(); types.add("type1"); types.add("type2"); final List<String> expectedAssignedWorkFlowTypes = new ArrayList<>(); when(stateRepository.findAllTypeByOwnerAndStatus(ownerIds, types)).thenReturn(expectedAssignedWorkFlowTypes); final List<String> actualAssignedWorkFlowTypes = stateService.getAssignedWorkflowTypeNames(ownerIds, types); assertEquals(expectedAssignedWorkFlowTypes, actualAssignedWorkFlowTypes); }
|
### Question:
StateService { public boolean isPositionUnderWorkflow(final Long posId, final Date givenDate) { return stateRepository.countByOwnerPositionAndCreatedDateGreaterThanEqual(posId, givenDate) > 0; } @Autowired StateService(final StateRepository stateRepository); boolean isPositionUnderWorkflow(final Long posId, final Date givenDate); List<String> getAssignedWorkflowTypeNames(List<Long> ownerIds,List<String> enabledTypes); State getStateByIdAndTenantId(final Long id, final String tenantId); @Transactional State create(final State state); @Transactional State update(final State state); }### Answer:
@Test public void testShouldVerifyWhetherThePositionExistsUnderWorkflow() { final Boolean expectedResult = true; final Long count = 2L; final Date date = new Date(); when(stateRepository.countByOwnerPositionAndCreatedDateGreaterThanEqual(34L, date)).thenReturn(count); final Boolean actualResult = stateService.isPositionUnderWorkflow(34L, date); assertEquals(expectedResult, actualResult); }
@Test public void testShouldVerifyPositionUnderWorkflow() { final Boolean expectedResult = false; final Long count = 0L; final Date date = new Date(); when(stateRepository.countByOwnerPositionAndCreatedDateGreaterThanEqual(34L, date)).thenReturn(count); final Boolean actualResult = stateService.isPositionUnderWorkflow(34L, date); assertEquals(expectedResult, actualResult); }
|
### Question:
TenantRepository { public City fetchTenantByCode(String tenant) { String url = this.tenantServiceHost + "tenant/v1/tenant/_search?code=" + tenant; final RequestInfoBody requestInfoBody = new RequestInfoBody(RequestInfo.builder().build()); final HttpEntity<RequestInfoBody> request = new HttpEntity<>(requestInfoBody); TenantResponse tr = restTemplate.postForObject(url, request, TenantResponse.class); if (!CollectionUtils.isEmpty(tr.getTenant())) return tr.getTenant().get(0).getCity(); else return null; } TenantRepository(RestTemplate restTemplate, @Value("${egov.services.tenant.host}") String tenantServiceHost); City fetchTenantByCode(String tenant); }### Answer:
@Test public void test_should_fetch_tenant_for_given_id() throws Exception { server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(resources.getFileContents("successTenantResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final City city = tenantRepository.fetchTenantByCode("default"); server.verify(); assertEquals("default", city.getName()); assertEquals("default", city.getCode()); }
@Test public void test_should_fail_when_tenant_id_null() throws Exception { server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(resources.getFileContents("failureTenantResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final City city = tenantRepository.fetchTenantByCode(null); server.verify(); assertNull(city); }
|
### Question:
KeywordStatusMappingService { public List<ComplaintStatus> getStatusForKeyword(KeywordStatusMappingSearchCriteria searchCriteria){ return keywordStatusMappingRepository.getAllStatusForKeyword(searchCriteria.getKeyword(), searchCriteria.getTenantId()); } KeywordStatusMappingService(KeywordStatusMappingRepository keywordStatusMappingRepository); List<ComplaintStatus> getStatusForKeyword(KeywordStatusMappingSearchCriteria searchCriteria); }### Answer:
@Test public void test_should_return_status_given_keyword() throws Exception{ List<ComplaintStatus> statusMappings = getKeywordStatusList(); when(keywordStatusMappingService.getStatusForKeyword(new KeywordStatusMappingSearchCriteria("Complaint","default"))) .thenReturn(statusMappings); List<ComplaintStatus> expectedKeywordMappings = keywordStatusMappingService .getStatusForKeyword(new KeywordStatusMappingSearchCriteria("Complaint","default")); assertThat(expectedKeywordMappings).isEqualTo(statusMappings); }
|
### Question:
ComplaintStatusService { public List<ComplaintStatus> findAll() { return complaintStatusRepository.findAll(); } ComplaintStatusService(ComplaintStatusRepository complaintStatusRepository,
ComplaintStatusMappingRepository complaintStatusMappingRepository); List<ComplaintStatus> findAll(); List<ComplaintStatus> getNextStatuses(ComplaintStatusSearchCriteria complaintStatusSearchCriteria); }### Answer:
@Test public void test_should_find_all_statuses() { List<ComplaintStatus> complaintStatuses = getListOfComplaintStatusModels(); when(complaintStatusRepository.findAll()).thenReturn(complaintStatuses); List<ComplaintStatus> all = complaintStatusService.findAll(); assertThat(all).isEqualTo(complaintStatuses); }
|
### Question:
EscalationService { public int getEscalationHours(EscalationHoursSearchCriteria searchCriteria) { return escalationRepository.getEscalationHours(searchCriteria); } EscalationService(EscalationRepository escalationRepository); int getEscalationHours(EscalationHoursSearchCriteria searchCriteria); EscalationTimeTypeReq create(EscalationTimeTypeReq escalationTimeTypeReq); EscalationTimeTypeReq update(EscalationTimeTypeReq escalationTimeTypeReq); List<EscalationTimeType> getAllEscalationTimeTypes(final EscalationTimeTypeGetReq escalationGetRequest); boolean checkRecordExists(EscalationTimeTypeReq escalationTimeTypeReq); static final Logger logger; }### Answer:
@Test public void test_should_return_escalation_hours_for_given_criteria() { final EscalationHoursSearchCriteria searchCriteria = EscalationHoursSearchCriteria.builder().build(); final int expectedEscalationHours = 3; when(escalationRepository.getEscalationHours(searchCriteria)).thenReturn(expectedEscalationHours); final int actualEscalationHours = escalationService.getEscalationHours(searchCriteria); assertEquals(expectedEscalationHours, actualEscalationHours); }
|
### Question:
IndexerListener { @KafkaListener(topics = "${kafka.topics.egov.index.name}") public void listen(HashMap<String, Object> receiptRequestMap) { ReceiptRequest receiptRequest = objectMapper.convertValue(receiptRequestMap, ReceiptRequest.class); final List<ReceiptRequestDocument> documents = documentService.enrich(receiptRequest); log.debug("Documents pushed to elastic search : "+ documents.size() + " and ",documents); elasticSearchRepository.index(documents); } @Autowired IndexerListener(ElasticSearchRepository elasticSearchRepository,
ObjectMapper objectMapper,
DocumentService documentService); @KafkaListener(topics = "${kafka.topics.egov.index.name}") void listen(HashMap<String, Object> receiptRequestMap); }### Answer:
@Test public void test_should_index_document() { final List<ReceiptRequestDocument> expectedDocumentToIndex = new ArrayList<ReceiptRequestDocument>(); final HashMap<String, Object> sevaRequestMap = getReceiptRequestMap(); when(documentService.enrich(any(ReceiptRequest.class))).thenReturn(expectedDocumentToIndex); indexerListener.listen(sevaRequestMap); verify(elasticSearchRepository).index(expectedDocumentToIndex); }
|
### Question:
UserRepository { public boolean isUserPresent(String userName, String tenantId, UserType userType) { String query = userTypeQueryBuilder.getUserPresentByUserNameAndTenant(); final Map<String, Object> parametersMap = new HashMap<String, Object>(); parametersMap.put("userName", userName); parametersMap.put("tenantId", tenantId); parametersMap.put("userType", userType.toString()); int count = namedParameterJdbcTemplate.queryForObject(query, parametersMap, Integer.class); return count > 0; } @Autowired UserRepository(RoleRepository roleRepository, UserTypeQueryBuilder userTypeQueryBuilder,
AddressRepository addressRepository, UserResultSetExtractor userResultSetExtractor,
JdbcTemplate jdbcTemplate,
NamedParameterJdbcTemplate namedParameterJdbcTemplate); List<User> findAll(UserSearchCriteria userSearch); boolean isUserPresent(String userName, String tenantId, UserType userType); User create(User user); void update(final User user, User oldUser); void fetchFailedLoginAttemptsByUser(String uuid); List<FailedLoginAttempt> fetchFailedAttemptsByUserAndTime(String uuid, long attemptStartDate); FailedLoginAttempt insertFailedLoginAttempt(FailedLoginAttempt failedLoginAttempt); void resetFailedLoginAttemptsForUser(String uuid); }### Answer:
@Test @Sql(scripts = { "/sql/clearUserRoles.sql","/sql/clearUsers.sql", "/sql/createUsers.sql" }) public void test_should_return_true_when_user_exists_with_given_user_name_and_tenant() { boolean isPresent = userRepository.isUserPresent("bigcat399", "ap.public", UserType.EMPLOYEE); assertTrue(isPresent); }
@Test public void test_should_return_false_when_user_does_not_exist_with_given_user_name_and_tenant() { boolean isPresent = userRepository.isUserPresent("userName", "ap.public", UserType.EMPLOYEE); assertFalse(isPresent); }
|
### Question:
StatusRepository { public List<Status> getStatuses(StatusCriteria criteria) { List<Object> preparedStatementValues = new ArrayList<>(); String queryString = statusQueryBuilder.getQuery(criteria, preparedStatementValues); return jdbcTemplate.query(queryString, preparedStatementValues.toArray(), statusRowMapper); } List<Status> getStatuses(StatusCriteria criteria); }### Answer:
@Test public void test_should_get_all_statuses_as_Per_criteria() { when(statusQueryBuilder.getQuery(any(StatusCriteria.class), any(List.class))).thenReturn(""); when(jdbcTemplate.query(any(String.class), any(Object[].class), any(StatusRowMapper.class))) .thenReturn(getStatusModel()); List<Status> actualStatuses = statusRepository.getStatuses(getStatusCriteria()); assertTrue(actualStatuses.get(0).equals(getStatusModel().get(0))); }
|
### Question:
OtpRepository { public boolean validateOtp(OtpValidateRequest request) { try { OtpResponse otpResponse = restTemplate.postForObject(otpValidateEndpoint, request, OtpResponse.class); if(null!=otpResponse && null!=otpResponse.getOtp()) return otpResponse.getOtp().isValidationSuccessful(); else return false; }catch(HttpClientErrorException e){ log.error("Otp validation failed", e); throw new ServiceCallException(e.getResponseBodyAsString()); } } @Autowired OtpRepository(@Value("${egov.otp.host}") String otpServiceHost,
@Value("${egov.services.otp.search_otp}") String otpSearchContextEndpoint,
@Value("${egov.services.otp.validate_otp}") String otpValidateEndpoint,
RestTemplate restTemplate); boolean isOtpValidationComplete(OtpValidationRequest request); boolean validateOtp(OtpValidateRequest request); }### Answer:
@Test @Ignore public void testShouldReturnTrueWhenOtpInValidated() throws Exception { server.expect(once(), requestTo("http: .andExpect(content().string(new Resources().getFileContents("otpValidationRequest.json"))) .andRespond(withSuccess(new Resources().getFileContents("otpNonValidateResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final OtpValidateRequest request = buildValidateRequest(); boolean isOtpValidated = otpRepository.validateOtp(request); server.verify(); assertEquals(Boolean.FALSE, isOtpValidated); }
@Test @Ignore public void testShouldReturnTrueWhenOtpValidated() throws Exception { server.expect(once(), requestTo("http: .andExpect(content().string(new Resources().getFileContents("otpValidationRequest.json"))) .andRespond(withSuccess(new Resources().getFileContents("otpValidateResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final OtpValidateRequest request = buildValidateRequest(); boolean isOtpValidated = otpRepository.validateOtp(request); server.verify(); assertEquals(Boolean.TRUE, isOtpValidated); }
|
### Question:
AddressRepository { public List<Address> find(Long userId, String tenantId) { final Map<String, Object> Map = new HashMap<String, Object>(); Map.put("userId", userId); Map.put("tenantId", tenantId); List<Address> addressList = namedParameterJdbcTemplate.query(GET_ADDRESS_BY_USERID, Map, new AddressRowMapper()); return addressList; } AddressRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate, JdbcTemplate jdbcTemplate); Address create(Address address, Long userId, String tenantId); void update(List<Address> domainAddresses, Long userId, String tenantId); List<Address> find(Long userId, String tenantId); static final String GET_ADDRESS_BY_USERID; static final String INSERT_ADDRESS_BYUSERID; static final String SELECT_NEXT_SEQUENCE; static final String DELETE_ADDRESSES; static final String DELETE_ADDRESS; static final String UPDATE_ADDRESS_BYIDAND_TENANTID; }### Answer:
@Test @Sql(scripts = { "/sql/clearAddresses.sql","/sql/clearUserRoles.sql","/sql/clearUsers.sql","/sql/createUsers.sql","/sql/createAddresses.sql"}) public void test_should_return_addresses_for_given_user_id_and_tenant() { final List<Address> actualAddresses = addressRepository.find(1L, "ap.public"); assertNotNull(actualAddresses); assertEquals(2, actualAddresses.size()); }
|
### Question:
StatusQueryBuilder { @SuppressWarnings("rawtypes") public String getQuery(StatusCriteria criteria, List preparedStatementValues) { StringBuilder selectQuery = new StringBuilder(BASE_QUERY); addWhereClause(selectQuery, preparedStatementValues, criteria); logger.debug("Query : " + selectQuery); return selectQuery.toString(); } @SuppressWarnings("rawtypes") String getQuery(StatusCriteria criteria, List preparedStatementValues); }### Answer:
@Test public void no_input_test() { StatusCriteria statusCriteria = new StatusCriteria(); StatusQueryBuilder builder = new StatusQueryBuilder(); assertEquals( "select id,code,objecttype,description,tenantId,createdBy," + "createdDate,lastModifiedBy,lastModifiedDate FROM egcl_status", builder.getQuery(statusCriteria, new ArrayList<>())); }
@Test public void all_input_test(){ StatusCriteria statusCriteria = new StatusCriteria(); StatusQueryBuilder builder = new StatusQueryBuilder(); statusCriteria.setCode("Submitted"); statusCriteria.setObjectType("ReceiptHeader"); statusCriteria.setTenantId("default"); assertEquals( "select id,code,objecttype,description,tenantId,createdBy," + "createdDate,lastModifiedBy,lastModifiedDate FROM egcl_status" +" WHERE tenantId = ? AND code = ? AND objecttype = ?", builder.getQuery(statusCriteria, new ArrayList<>())); }
|
### Question:
PasswordController { @PostMapping("/nologin/_update") public UpdatePasswordResponse updatePasswordForNonLoggedInUser(@RequestBody NonLoggedInUserUpdatePasswordRequest request) { userService.updatePasswordForNonLoggedInUser(request.toDomain()); return new UpdatePasswordResponse(ResponseInfo.builder().status(String.valueOf(HttpStatus.OK.value())).build()); } PasswordController(UserService userService); @PostMapping("/_update") UpdatePasswordResponse updatePassword(@RequestBody LoggedInUserUpdatePasswordRequest request); @PostMapping("/nologin/_update") UpdatePasswordResponse updatePasswordForNonLoggedInUser(@RequestBody NonLoggedInUserUpdatePasswordRequest request); }### Answer:
@Test @WithMockUser public void test_should_update_password_for_non_logged_in_user() throws Exception { mockMvc.perform(post("/password/nologin/_update") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(resources.getFileContents("nonLoggedInUserUpdatePasswordRequest.json"))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(content().json(resources.getFileContents("updatePasswordResponse.json"))); final NonLoggedInUserUpdatePasswordRequest expectedRequest = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId("tenant") .newPassword("newPassword") .otpReference("otpReference") .userName("userName") .build(); verify(userService).updatePasswordForNonLoggedInUser(expectedRequest); }
|
### Question:
UserController { @PostMapping("/_details") public CustomUserDetails getUser(@RequestParam(value = "access_token") String accessToken) { final UserDetail userDetail = tokenService.getUser(accessToken); return new CustomUserDetails(userDetail); } @Autowired UserController(UserService userService, TokenService tokenService); @PostMapping("/citizen/_create") Object createCitizen(@RequestBody CreateUserRequest createUserRequest); @PostMapping("/users/_createnovalidate") UserDetailResponse createUserWithoutValidation(@RequestBody CreateUserRequest createUserRequest,
@RequestHeader HttpHeaders headers); @PostMapping("/_search") UserSearchResponse get(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers); @PostMapping("/v1/_search") UserSearchResponse getV1(@RequestBody UserSearchRequest request, @RequestHeader HttpHeaders headers); @PostMapping("/_details") CustomUserDetails getUser(@RequestParam(value = "access_token") String accessToken); @PostMapping("/users/_updatenovalidate") UserDetailResponse updateUserWithoutValidation(@RequestBody final CreateUserRequest createUserRequest,
@RequestHeader HttpHeaders headers); @PostMapping("/profile/_update") UserDetailResponse patch(@RequestBody final CreateUserRequest createUserRequest); }### Answer:
@Test @WithMockUser public void testUserDetails() throws Exception { OAuth2Authentication oAuth2Authentication = mock(OAuth2Authentication.class); SecureUser secureUser = new SecureUser(getUser()); when(oAuth2Authentication.getPrincipal()).thenReturn(secureUser); when(tokenService.getUser("c80e0ade-f48d-4077-b0d2-4e58526a6bfd")) .thenReturn(getCustomUserDetails()); mockMvc.perform(post("/_details?access_token=c80e0ade-f48d-4077-b0d2-4e58526a6bfd")) .andExpect(status().isOk()) .andExpect(content().json(getFileContents("userDetailsResponse.json"))); }
|
### Question:
NonLoggedInUserUpdatePasswordRequest { public org.egov.user.domain.model.NonLoggedInUserUpdatePasswordRequest toDomain() { return org.egov.user.domain.model.NonLoggedInUserUpdatePasswordRequest.builder().otpReference(otpReference) .userName(userName).newPassword(newPassword).type(type).tenantId(tenantId).build(); } org.egov.user.domain.model.NonLoggedInUserUpdatePasswordRequest toDomain(); }### Answer:
@Test public void test_should_map_from_contract_to_domain() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .newPassword("newPassword") .userName("userName") .otpReference("otpReference") .tenantId("tenant") .build(); final org.egov.user.domain.model.NonLoggedInUserUpdatePasswordRequest domain = request.toDomain(); assertNotNull(domain); assertEquals("userName", domain.getUserName()); assertEquals("newPassword", domain.getNewPassword()); assertEquals("otpReference", domain.getOtpReference()); assertEquals("tenant", domain.getTenantId()); }
|
### Question:
UserSearchRequest { public UserSearchCriteria toDomain() { return UserSearchCriteria.builder() .id(id) .userName(userName) .name(name) .mobileNumber(mobileNumber) .emailId(emailId) .fuzzyLogic(fuzzyLogic) .active(active) .limit(pageSize) .offset(pageNumber) .sort(sort) .type(UserType.fromValue(userType)) .tenantId(tenantId) .roleCodes(roleCodes) .uuid(uuid) .build(); } UserSearchCriteria toDomain(); }### Answer:
@Test public void test_to_domain() throws Exception { List<Long> ids = Arrays.asList(1L, 2L, 3L); UserSearchRequest userSearchRequest = new UserSearchRequest(); userSearchRequest.setId(ids); userSearchRequest.setUserName("userName"); userSearchRequest.setName("name"); userSearchRequest.setMobileNumber("mobileNumber"); userSearchRequest.setAadhaarNumber("aadhaarNumber"); userSearchRequest.setEmailId("emailId"); userSearchRequest.setPan("pan"); userSearchRequest.setFuzzyLogic(false); userSearchRequest.setActive(true); userSearchRequest.setUserType("CITIZEN"); UserSearchCriteria userSearch = userSearchRequest.toDomain(); assertThat(userSearch.getId()).isEqualTo(ids); assertThat(userSearch.getUserName()).isEqualTo("userName"); assertThat(userSearch.getName()).isEqualTo("name"); assertThat(userSearch.getMobileNumber()).isEqualTo("mobileNumber"); assertThat(userSearch.getEmailId()).isEqualTo("emailId"); assertThat(userSearch.isFuzzyLogic()).isFalse(); assertThat(userSearch.getActive()).isTrue(); assertThat(userSearch.getLimit()).isEqualTo(0); assertThat(userSearch.getOffset()).isEqualTo(0); assertThat(userSearch.getSort()).isEqualTo(Collections.singletonList("name")); assertThat(userSearch.getType()).isEqualTo(UserType.CITIZEN); }
|
### Question:
NonLoggedInUserUpdatePasswordRequest { public void validate() { if (isModelInvalid()) { throw new InvalidNonLoggedInUserUpdatePasswordRequestException(this); } } void validate(); OtpValidationRequest getOtpValidationRequest(); boolean isOtpReferenceAbsent(); boolean isUsernameAbsent(); boolean isNewPasswordAbsent(); boolean isTenantIdAbsent(); }### Answer:
@Test(expected = InvalidNonLoggedInUserUpdatePasswordRequestException.class) public void test_should_throw_exception_when_tenant_id_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId(null) .newPassword("newPassword") .userName("userName") .otpReference("otpReference") .build(); request.validate(); }
@Test(expected = InvalidNonLoggedInUserUpdatePasswordRequestException.class) public void test_should_throw_exception_when_new_password_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId("tenantId") .newPassword(null) .userName("userName") .otpReference("otpReference") .build(); request.validate(); }
@Test(expected = InvalidNonLoggedInUserUpdatePasswordRequestException.class) public void test_should_throw_exception_when_mobile_number_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId("tenantId") .newPassword("newPassword") .userName(null) .otpReference("otpReference") .build(); request.validate(); }
@Test(expected = InvalidNonLoggedInUserUpdatePasswordRequestException.class) public void test_should_throw_exception_when_otp_reference_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId("tenantId") .newPassword("newPassword") .userName("userName") .otpReference(null) .build(); request.validate(); }
|
### Question:
NonLoggedInUserUpdatePasswordRequest { public boolean isTenantIdAbsent() { return isEmpty(tenantId); } void validate(); OtpValidationRequest getOtpValidationRequest(); boolean isOtpReferenceAbsent(); boolean isUsernameAbsent(); boolean isNewPasswordAbsent(); boolean isTenantIdAbsent(); }### Answer:
@Test public void test_should_return_true_when_tenant_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId(null) .newPassword("newPassword") .userName("userName") .otpReference("otpReference") .build(); assertTrue(request.isTenantIdAbsent()); }
|
### Question:
NonLoggedInUserUpdatePasswordRequest { public boolean isNewPasswordAbsent() { return isEmpty(newPassword); } void validate(); OtpValidationRequest getOtpValidationRequest(); boolean isOtpReferenceAbsent(); boolean isUsernameAbsent(); boolean isNewPasswordAbsent(); boolean isTenantIdAbsent(); }### Answer:
@Test public void test_should_return_true_when_new_password_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId("tenantId") .newPassword(null) .userName("userName") .otpReference("otpReference") .build(); assertTrue(request.isNewPasswordAbsent()); }
|
### Question:
NonLoggedInUserUpdatePasswordRequest { public boolean isUsernameAbsent() { return isEmpty(userName); } void validate(); OtpValidationRequest getOtpValidationRequest(); boolean isOtpReferenceAbsent(); boolean isUsernameAbsent(); boolean isNewPasswordAbsent(); boolean isTenantIdAbsent(); }### Answer:
@Test public void test_should_return_true_when_mobile_number_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId("tenantId") .newPassword("newPassword") .userName(null) .otpReference("otpReference") .build(); assertTrue(request.isUsernameAbsent()); }
|
### Question:
StatusService { public List<Status> getStatuses(StatusCriteria criteria) { return statusRepository.getStatuses(criteria); } List<Status> getStatuses(StatusCriteria criteria); }### Answer:
@Test public void test_should_get_all_status_by_criteria() { when(statusRepository.getStatuses(getStatusCriteria())).thenReturn(getStatusModel()); List<Status> statusModel = statusService.getStatuses(getStatusCriteria()); assertThat(statusModel.get(0).getCode()).isEqualTo(getStatusModel().get(0).getCode()); }
|
### Question:
NonLoggedInUserUpdatePasswordRequest { public boolean isOtpReferenceAbsent() { return isEmpty(otpReference); } void validate(); OtpValidationRequest getOtpValidationRequest(); boolean isOtpReferenceAbsent(); boolean isUsernameAbsent(); boolean isNewPasswordAbsent(); boolean isTenantIdAbsent(); }### Answer:
@Test public void test_should_return_true_when_otp_reference_is_not_present() { final NonLoggedInUserUpdatePasswordRequest request = NonLoggedInUserUpdatePasswordRequest.builder() .tenantId("tenantId") .newPassword("newPassword") .userName("userName") .otpReference(null) .build(); assertTrue(request.isOtpReferenceAbsent()); }
|
### Question:
User { public boolean isIdAbsent() { return id == null; } User addAddressItem(Address addressItem); User addRolesItem(Role roleItem); void validateNewUser(); void validateUserModification(); boolean isCorrespondenceAddressInvalid(); boolean isPermanentAddressInvalid(); boolean isOtpReferenceAbsent(); boolean isTypeAbsent(); boolean isActiveIndicatorAbsent(); boolean isMobileNumberAbsent(); boolean isNameAbsent(); boolean isUsernameAbsent(); boolean isTenantIdAbsent(); boolean isPasswordAbsent(); boolean isRolesAbsent(); boolean isIdAbsent(); void nullifySensitiveFields(); boolean isLoggedInUserDifferentFromUpdatedUser(); void setRoleToCitizen(); void updatePassword(String newPassword); OtpValidationRequest getOtpValidationRequest(); List<Address> getPermanentAndCorrespondenceAddresses(); void setDefaultPasswordExpiry(int expiryInDays); void setActive(boolean isActive); }### Answer:
@Test public void test_should_return_true_when_user_id_is_not_present() { User user = User.builder() .id(null) .build(); assertTrue(user.isIdAbsent()); }
@Test public void test_should_return_false_when_user_id_is_present() { User user = User.builder() .id(123L) .build(); assertFalse(user.isIdAbsent()); }
|
### Question:
User { public void validateNewUser() { if (isUsernameAbsent() || isNameAbsent() || isMobileNumberAbsent() || isActiveIndicatorAbsent() || isTypeAbsent() || isPermanentAddressInvalid() || isCorrespondenceAddressInvalid() || isRolesAbsent() || isOtpReferenceAbsent() || isTenantIdAbsent()){ throw new InvalidUserCreateException(this); } } User addAddressItem(Address addressItem); User addRolesItem(Role roleItem); void validateNewUser(); void validateUserModification(); boolean isCorrespondenceAddressInvalid(); boolean isPermanentAddressInvalid(); boolean isOtpReferenceAbsent(); boolean isTypeAbsent(); boolean isActiveIndicatorAbsent(); boolean isMobileNumberAbsent(); boolean isNameAbsent(); boolean isUsernameAbsent(); boolean isTenantIdAbsent(); boolean isPasswordAbsent(); boolean isRolesAbsent(); boolean isIdAbsent(); void nullifySensitiveFields(); boolean isLoggedInUserDifferentFromUpdatedUser(); void setRoleToCitizen(); void updatePassword(String newPassword); OtpValidationRequest getOtpValidationRequest(); List<Address> getPermanentAndCorrespondenceAddresses(); void setDefaultPasswordExpiry(int expiryInDays); void setActive(boolean isActive); }### Answer:
@Test(expected = InvalidUserCreateException.class) public void test_should_throw_validation_exception_when_otp_reference_is_not_present_and_mandatory_flag_is_enabled() { User user = User.builder() .otpReference(null) .otpValidationMandatory(true) .build(); user.validateNewUser(); }
|
### Question:
User { public boolean isOtpReferenceAbsent() { return otpValidationMandatory && isEmpty(otpReference); } User addAddressItem(Address addressItem); User addRolesItem(Role roleItem); void validateNewUser(); void validateUserModification(); boolean isCorrespondenceAddressInvalid(); boolean isPermanentAddressInvalid(); boolean isOtpReferenceAbsent(); boolean isTypeAbsent(); boolean isActiveIndicatorAbsent(); boolean isMobileNumberAbsent(); boolean isNameAbsent(); boolean isUsernameAbsent(); boolean isTenantIdAbsent(); boolean isPasswordAbsent(); boolean isRolesAbsent(); boolean isIdAbsent(); void nullifySensitiveFields(); boolean isLoggedInUserDifferentFromUpdatedUser(); void setRoleToCitizen(); void updatePassword(String newPassword); OtpValidationRequest getOtpValidationRequest(); List<Address> getPermanentAndCorrespondenceAddresses(); void setDefaultPasswordExpiry(int expiryInDays); void setActive(boolean isActive); }### Answer:
@Test public void test_should_return_true_when_otp_reference_is_not_present_and_mandatory_flag_is_enabled() { User user = User.builder() .otpReference(null) .otpValidationMandatory(true) .build(); assertTrue(user.isOtpReferenceAbsent()); }
@Test public void test_should_return_false_when_otp_reference_is_not_present_and_mandatory_flag_is_false() { User user = User.builder() .otpReference(null) .otpValidationMandatory(false) .build(); assertFalse(user.isOtpReferenceAbsent()); }
@Test public void test_should_return_false_when_otp_reference_is_present() { User user = User.builder() .otpReference("otpReference") .build(); assertFalse(user.isOtpReferenceAbsent()); }
|
### Question:
User { public boolean isLoggedInUserDifferentFromUpdatedUser() { return !id.equals(loggedInUserId); } User addAddressItem(Address addressItem); User addRolesItem(Role roleItem); void validateNewUser(); void validateUserModification(); boolean isCorrespondenceAddressInvalid(); boolean isPermanentAddressInvalid(); boolean isOtpReferenceAbsent(); boolean isTypeAbsent(); boolean isActiveIndicatorAbsent(); boolean isMobileNumberAbsent(); boolean isNameAbsent(); boolean isUsernameAbsent(); boolean isTenantIdAbsent(); boolean isPasswordAbsent(); boolean isRolesAbsent(); boolean isIdAbsent(); void nullifySensitiveFields(); boolean isLoggedInUserDifferentFromUpdatedUser(); void setRoleToCitizen(); void updatePassword(String newPassword); OtpValidationRequest getOtpValidationRequest(); List<Address> getPermanentAndCorrespondenceAddresses(); void setDefaultPasswordExpiry(int expiryInDays); void setActive(boolean isActive); }### Answer:
@Test public void test_should_return_false_when_logged_in_user_is_same_as_user_being_updated() { User user = User.builder() .id(1L) .loggedInUserId(1L) .build(); assertFalse(user.isLoggedInUserDifferentFromUpdatedUser()); }
@Test public void test_should_return_true_when_logged_in_user_is_different_from_user_being_updated() { User user = User.builder() .id(1L) .loggedInUserId(2L) .build(); assertTrue(user.isLoggedInUserDifferentFromUpdatedUser()); }
|
### Question:
User { public void setRoleToCitizen() { type = UserType.CITIZEN; roles = Collections.singleton(Role.getCitizenRole()); } User addAddressItem(Address addressItem); User addRolesItem(Role roleItem); void validateNewUser(); void validateUserModification(); boolean isCorrespondenceAddressInvalid(); boolean isPermanentAddressInvalid(); boolean isOtpReferenceAbsent(); boolean isTypeAbsent(); boolean isActiveIndicatorAbsent(); boolean isMobileNumberAbsent(); boolean isNameAbsent(); boolean isUsernameAbsent(); boolean isTenantIdAbsent(); boolean isPasswordAbsent(); boolean isRolesAbsent(); boolean isIdAbsent(); void nullifySensitiveFields(); boolean isLoggedInUserDifferentFromUpdatedUser(); void setRoleToCitizen(); void updatePassword(String newPassword); OtpValidationRequest getOtpValidationRequest(); List<Address> getPermanentAndCorrespondenceAddresses(); void setDefaultPasswordExpiry(int expiryInDays); void setActive(boolean isActive); }### Answer:
@Test public void test_should_override_to_citizen_role() { User user = User.builder() .id(1L) .type(UserType.CITIZEN) .roles(Collections.singleton(Role.builder().code("ADMIN").build())) .build(); user.setRoleToCitizen(); assertEquals(UserType.CITIZEN, user.getType()); final Set<Role> roles = user.getRoles(); assertEquals(1, roles.size()); assertEquals("CITIZEN", roles.iterator().next().getCode()); }
|
### Question:
User { public void nullifySensitiveFields() { username = null; type = null; mobileNumber = null; password = null; passwordExpiryDate = null; roles = null; accountLocked = null; accountLockedDate = null; } User addAddressItem(Address addressItem); User addRolesItem(Role roleItem); void validateNewUser(); void validateUserModification(); boolean isCorrespondenceAddressInvalid(); boolean isPermanentAddressInvalid(); boolean isOtpReferenceAbsent(); boolean isTypeAbsent(); boolean isActiveIndicatorAbsent(); boolean isMobileNumberAbsent(); boolean isNameAbsent(); boolean isUsernameAbsent(); boolean isTenantIdAbsent(); boolean isPasswordAbsent(); boolean isRolesAbsent(); boolean isIdAbsent(); void nullifySensitiveFields(); boolean isLoggedInUserDifferentFromUpdatedUser(); void setRoleToCitizen(); void updatePassword(String newPassword); OtpValidationRequest getOtpValidationRequest(); List<Address> getPermanentAndCorrespondenceAddresses(); void setDefaultPasswordExpiry(int expiryInDays); void setActive(boolean isActive); }### Answer:
@Test public void test_should_nullify_fields() { Role role1 = Role.builder().code("roleCode1").build(); Role role2 = Role.builder().code("roleCode2").build(); User user = User.builder() .username("userName") .mobileNumber("mobileNumber") .password("password") .passwordExpiryDate(new Date()) .roles(new HashSet<>(Arrays.asList(role1, role2))) .build(); user.nullifySensitiveFields(); assertNull(user.getUsername()); assertNull(user.getMobileNumber()); assertNull(user.getPassword()); assertNull(user.getPasswordExpiryDate()); assertNull(user.getRoles()); }
|
### Question:
User { public OtpValidationRequest getOtpValidationRequest() { return OtpValidationRequest.builder() .mobileNumber(mobileNumber) .tenantId(tenantId) .otpReference(otpReference) .build(); } User addAddressItem(Address addressItem); User addRolesItem(Role roleItem); void validateNewUser(); void validateUserModification(); boolean isCorrespondenceAddressInvalid(); boolean isPermanentAddressInvalid(); boolean isOtpReferenceAbsent(); boolean isTypeAbsent(); boolean isActiveIndicatorAbsent(); boolean isMobileNumberAbsent(); boolean isNameAbsent(); boolean isUsernameAbsent(); boolean isTenantIdAbsent(); boolean isPasswordAbsent(); boolean isRolesAbsent(); boolean isIdAbsent(); void nullifySensitiveFields(); boolean isLoggedInUserDifferentFromUpdatedUser(); void setRoleToCitizen(); void updatePassword(String newPassword); OtpValidationRequest getOtpValidationRequest(); List<Address> getPermanentAndCorrespondenceAddresses(); void setDefaultPasswordExpiry(int expiryInDays); void setActive(boolean isActive); }### Answer:
@Test public void test_should_map_from_user_to_otp_validation_request() { final User user = User.builder() .tenantId("tenantId") .otpReference("otpReference") .mobileNumber("mobileNumber") .build(); final OtpValidationRequest otpValidationRequest = user.getOtpValidationRequest(); assertNotNull(otpValidationRequest); assertEquals("tenantId", otpValidationRequest.getTenantId()); assertEquals("mobileNumber", otpValidationRequest.getMobileNumber()); assertEquals("otpReference", otpValidationRequest.getOtpReference()); }
|
### Question:
Address { boolean isInvalid() { return isPinCodeInvalid() || isCityInvalid() || isAddressInvalid(); } }### Answer:
@Test public void test_invalid_should_return_false_when_all_fields_are_within_length_limit() { final Address address = Address.builder() .address(multiplyCharacter(300, "A")) .city(multiplyCharacter(300, "B")) .pinCode(multiplyCharacter(10, "A")) .build(); assertFalse(address.isInvalid()); }
|
### Question:
LoggedInUserUpdatePasswordRequest { public void validate() { if (isUsernameAbsent() || isTenantAbsent() || isUserTypeAbsent() || isExistingPasswordAbsent() || isNewPasswordAbsent()) { throw new InvalidLoggedInUserUpdatePasswordRequestException(this); } } void validate(); boolean isUsernameAbsent(); boolean isExistingPasswordAbsent(); boolean isNewPasswordAbsent(); boolean isTenantAbsent(); boolean isUserTypeAbsent(); }### Answer:
@Test public void test_validate_should_not_throw_exception_when_all_mandatory_fields_are_present() { final LoggedInUserUpdatePasswordRequest updatePassword = LoggedInUserUpdatePasswordRequest.builder() .existingPassword("existingPassword") .newPassword("newPassword") .userName("greenfish424") .tenantId("ap.public") .type(UserType.CITIZEN) .build(); updatePassword.validate(); }
@Test(expected = InvalidLoggedInUserUpdatePasswordRequestException.class) public void test_validate_should_throw_exception_when_user_id_is_not_present() { final LoggedInUserUpdatePasswordRequest updatePassword = LoggedInUserUpdatePasswordRequest.builder() .existingPassword("existingPassword") .newPassword("newPassword") .userName(null) .build(); updatePassword.validate(); }
@Test(expected = InvalidLoggedInUserUpdatePasswordRequestException.class) public void test_validate_should_throw_exception_when_old_password_is_not_present() { final LoggedInUserUpdatePasswordRequest updatePassword = LoggedInUserUpdatePasswordRequest.builder() .existingPassword(null) .newPassword("newPassword") .userName("xya") .build(); updatePassword.validate(); }
@Test(expected = InvalidLoggedInUserUpdatePasswordRequestException.class) public void test_validate_should_throw_exception_when_new_password_is_not_present() { final LoggedInUserUpdatePasswordRequest updatePassword = LoggedInUserUpdatePasswordRequest.builder() .existingPassword("existingPassword") .newPassword(null) .userName("xyz") .build(); updatePassword.validate(); }
|
### Question:
UserSearchCriteria { public void validate(boolean isInterServiceCall) { if (validateIfEmptySearch(isInterServiceCall) || validateIfTenantIdExists(isInterServiceCall)) { throw new InvalidUserSearchCriteriaException(this); } } void validate(boolean isInterServiceCall); }### Answer:
@Test public void test_should_not_throw_exception_when_search_criteria_is_valid() { final UserSearchCriteria searchCriteria = UserSearchCriteria.builder() .tenantId("tenantId") .userName("greenfish424") .build(); searchCriteria.validate(true); }
@Test(expected = InvalidUserSearchCriteriaException.class) public void test_should_throw_exception_when_tenant_id_is_not_present() { final UserSearchCriteria searchCriteria = UserSearchCriteria.builder() .tenantId(null) .build(); searchCriteria.validate(true); }
|
### Question:
TokenService { public UserDetail getUser(String accessToken) { if (StringUtils.isEmpty(accessToken)) { throw new InvalidAccessTokenException(); } OAuth2Authentication authentication = tokenStore.readAuthentication(accessToken); if (authentication == null) { throw new InvalidAccessTokenException(); } SecureUser secureUser = ((SecureUser) authentication.getPrincipal()); return new UserDetail(secureUser, null); } private TokenService(TokenStore tokenStore, ActionRestRepository actionRestRepository); UserDetail getUser(String accessToken); }### Answer:
@Test public void test_should_get_user_details_for_given_token() { OAuth2Authentication oAuth2Authentication = mock(OAuth2Authentication.class); final String accessToken = "c80e0ade-f48d-4077-b0d2-4e58526a6bfd"; when(tokenStore.readAuthentication(accessToken)).thenReturn(oAuth2Authentication); SecureUser secureUser = new SecureUser(getUser()); when(oAuth2Authentication.getPrincipal()).thenReturn(secureUser); final List<Action> expectedActions = getActions(); when(actionRestRepository.getActionByRoleCodes(getRoleCodes(), "default")).thenReturn(expectedActions); UserDetail actualUserDetails = tokenService.getUser(accessToken); assertEquals(secureUser, actualUserDetails.getSecureUser()); }
@Test(expected = InvalidAccessTokenException.class) public void test_should_throw_exception_when_access_token_is_not_specified() { tokenService.getUser(""); }
@Test(expected = InvalidAccessTokenException.class) public void test_should_throw_exception_when_access_token_is_not_present_in_token_store() { when(tokenStore.readAuthentication("accessToken")).thenReturn(null); tokenService.getUser("accessToken"); }
|
### Question:
BoundaryRepository { public BoundaryResponse findBoundary(String latitude, String longitude,String tenantid) { final BoundaryServiceResponse serviceResponse = restTemplate.getForObject(this.url, BoundaryServiceResponse.class, latitude, longitude,tenantid); return serviceResponse.getBoundary(); } @Autowired BoundaryRepository(RestTemplate restTemplate,
@Value("${egov.services.boundary.host}") String boundaryServiceHost,
@Value("${egov.services.boundary.context.fetch_by_lat_lng}") String latLongUrl); BoundaryResponse findBoundary(String latitude, String longitude,String tenantid); }### Answer:
@Test public void test_should_fetch_location_for_given_coordinates() { server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.GET)) .andRespond( withSuccess(new Resources().getFileContents("successBoundaryResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final BoundaryResponse boundary = boundaryRepository.findBoundary("1.11", "2.22","ap.public"); server.verify(); assertEquals(Long.valueOf(1), boundary.getId()); assertEquals("foo", boundary.getName()); }
|
### Question:
Notification extends AbstractAuditable { public boolean isRead() { return YES.equalsIgnoreCase(read); } boolean isRead(); org.egov.domain.model.Notification toDomain(); static final String SEQ_NOTIFICATION; }### Answer:
@Test public void test_is_read_should_return_false_when_read_is_set_to_no() { Notification notification = new Notification(); notification.setRead("N"); assertThat(notification.isRead()).isFalse(); }
@Test public void test_is_read_should_return_true_when_read_is_set_to_yes() { Notification notification = new Notification(); notification.setRead("Y"); assertThat(notification.isRead()).isTrue(); }
|
### Question:
CrossHierarchyRepository { public CrossHierarchyResponse getCrossHierarchy(String crossHierarchyId, String tenantId) { CrossHierarchySearchRequest crossHierarchySearchRequest = getCrossHierarchySearchRequest(crossHierarchyId, tenantId); CrossHierarchyServiceResponse crossHierarchyServiceResponse = restTemplate.postForObject(url, crossHierarchySearchRequest, CrossHierarchyServiceResponse.class); return crossHierarchyServiceResponse.getCrossHierarchy(); } CrossHierarchyRepository(@Value("${egov.services.boundary.host}")
String crossHierarchyServiceHost,
@Value("${egov.services.boundary.context.fetch_by_hierarchy_id}")
String crossHierarchyUrl,
RestTemplate restTemplate); CrossHierarchyResponse getCrossHierarchy(String crossHierarchyId, String tenantId); }### Answer:
@Test public void test_should_fetch_hierarchy_for_given_id() { server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.POST)) .andRespond( withSuccess(new Resources().getFileContents("successHierarchyResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final CrossHierarchyResponse response = crossHierarchyRepository.getCrossHierarchy("5", "tenantId"); server.verify(); assertEquals("1", response.getLocationId()); assertEquals("parent", response.getLocationName()); assertEquals("2", response.getChildLocationId()); }
|
### Question:
ActionValidationRowMapper implements RowMapper<ActionValidation> { @Override public ActionValidation mapRow(ResultSet resultSet, int i) throws SQLException { return ActionValidation.builder().allowed(resultSet.getBoolean("exists")).build(); } @Override ActionValidation mapRow(ResultSet resultSet, int i); }### Answer:
@Test public void testActionValidationRowMapperShouldReturnTrueIfActionIsValidated() throws SQLException { ActionValidationRowMapper actionValidationRowMapper = new ActionValidationRowMapper(); when(resultSet.getBoolean("exists")).thenReturn(true); assert actionValidationRowMapper.mapRow(resultSet, 1).isAllowed(); when(resultSet.getBoolean("exists")).thenReturn(false); assertFalse(actionValidationRowMapper.mapRow(resultSet, 1).isAllowed()); }
|
### Question:
ValidateActionQueryBuilder implements BaseQueryBuilder { @Override public String build() { filterRoleNames(); filterTenantId(); filterActionUrl(); return BASE_QUERY + " WHERE " + String.join(" AND ", filters) + ") AS \"exists\""; } ValidateActionQueryBuilder(ValidateActionCriteria criteria); @Override String build(); }### Answer:
@Test public void testQueryToValidateAction() { ValidateActionCriteria criteria = ValidateActionCriteria.builder().roleNames(Arrays.asList("r1", "r2")) .actionUrl("url").tenantId("tenantid").build(); ValidateActionQueryBuilder builder = new ValidateActionQueryBuilder(criteria); String expectedQuery = "SELECT exists(SELECT 1 from eg_roleaction AS ra" + " JOIN eg_ms_role AS r ON ra.rolecode = r.code" + " JOIN eg_action AS a on ra.actionid = a.id" + " WHERE r.name in ('r1','r2')" + " AND ra.tenantid = 'tenantid'" + " AND a.url = 'url') AS \"exists\""; assertEquals(expectedQuery, builder.build()); }
|
### Question:
RoleFinderQueryBuilder implements BaseQueryBuilder { @Override public String build() { filterRoleCodes(); String filterQuery = shouldFilter() ? " WHERE " + String.join(" AND ", filters) : ""; return BASE_QUERY + filterQuery + " ORDER BY r_name"; } RoleFinderQueryBuilder(RoleSearchCriteria criteria); @Override String build(); }### Answer:
@Test public void testQueryToFindRoles() { RoleSearchCriteria criteria = RoleSearchCriteria.builder().codes(Arrays.asList("CITIZEN", "EMPLOYEE")).build(); RoleFinderQueryBuilder builder = new RoleFinderQueryBuilder(criteria); String expectedQuery = "SELECT r.name as r_name,r.code as r_code, r.description as r_description from eg_ms_role r " + "WHERE r.code in ('CITIZEN','EMPLOYEE') ORDER BY r_name"; assertEquals(expectedQuery, builder.build()); }
@Test public void testQueryToFindRolesWhenNoRoleCodes() { RoleSearchCriteria criteria = RoleSearchCriteria.builder().build(); RoleFinderQueryBuilder builder = new RoleFinderQueryBuilder(criteria); String expectedQuery = "SELECT r.name as r_name,r.code as r_code, r.description as r_description from eg_ms_role r " + "ORDER BY r_name"; assertEquals(expectedQuery, builder.build()); }
|
### Question:
ComplaintRepository { public void save(SevaRequest sevaRequest) { kafkaTemplate.send(topicName, sevaRequest.getRequestMap()); } @Autowired ComplaintRepository(@Value("${kafka.topics.pgr.boundary_enriched.name}") String topicName,
LogAwareKafkaTemplate<String, Object> kafkaTemplate); void save(SevaRequest sevaRequest); }### Answer:
@Test public void test_should_send_message() { final HashMap<String, Object> sevaRequestMap = new HashMap<>(); final SevaRequest sevaRequest = new SevaRequest(sevaRequestMap); complaintRepository.save(sevaRequest); verify(kafkaTemplate).send("topicName", sevaRequestMap); }
|
### Question:
RoleActionRepository { public boolean addUniqueValidationForTenantAndRoleAndAction(final RoleActionsRequest actionRequest) { List<Integer> actionList = getActionsBasedOnIds(actionRequest); if (actionList.size() > 0) { final Map<String, Object> parametersMap = new HashMap<String, Object>(); parametersMap.put("rolecode", actionRequest.getRole().getCode()); parametersMap.put("tenantid", actionRequest.getTenantId()); parametersMap.put("actionid", actionList); SqlRowSet sqlrowset = namedParameterJdbcTemplate.queryForRowSet(CHECK_UNIQUE_VALIDATION_FOR_ROLEACTIONS, parametersMap); if (sqlrowset != null && sqlrowset.next()) { String rolecode = sqlrowset.getString("rolecode"); if (rolecode != null && rolecode != "") { return false; } } } return true; } List<RoleAction> createRoleActions(final RoleActionsRequest actionRequest); boolean checkActionNamesAreExistOrNot(final RoleActionsRequest actionRequest); boolean addUniqueValidationForTenantAndRoleAndAction(final RoleActionsRequest actionRequest); static final Logger LOGGER; }### Answer:
@Test @Sql(scripts = { "/sql/clearRole.sql", "/sql/clearAction.sql", "/sql/insertRoleData.sql", "/sql/insertActionData.sql" }) public void testAddUniqueValidationForTenantAndRoleAndAction() { RoleActionsRequest roleActionRequest = new RoleActionsRequest(); Role role = Role.builder().code("PGR").build(); Action action1 = Action.builder().name("Get all ReceivingMode").build(); Action action2 = Action.builder().name("Get all CompaintTypeCategory").build(); List<Action> list = new ArrayList<Action>(); list.add(action1); list.add(action2); roleActionRequest.setActions(list); roleActionRequest.setRole(role); boolean exist = roleActionRepository.addUniqueValidationForTenantAndRoleAndAction(roleActionRequest); assertThat(exist == true); }
|
### Question:
GrievanceLocationEnrichmentListener { @KafkaListener(id = "${kafka.topics.pgr.validated.id}", topics = "${kafka.topics.pgr.validated.name}", group = "${kafka.topics.pgr.validated.group}") public void process(HashMap<String, Object> sevaRequestMap) { final SevaRequest sevaRequest = new SevaRequest(sevaRequestMap); final SevaRequest enrichedSevaRequest = locationService.enrich(sevaRequest); complaintRepository.save(enrichedSevaRequest); } @Autowired GrievanceLocationEnrichmentListener(LocationService locationService,
ComplaintRepository complaintRepository); @KafkaListener(id = "${kafka.topics.pgr.validated.id}", topics = "${kafka.topics.pgr.validated.name}", group = "${kafka.topics.pgr.validated.group}") void process(HashMap<String, Object> sevaRequestMap); }### Answer:
@Test public void test_should_perist_enriched_seva_request() { final HashMap<String, Object> sevaRequest = getSevaRequestMap(); final SevaRequest enrichedSevaRequest = new SevaRequest(new HashMap<>()); when(locationService.enrich(any())).thenReturn(enrichedSevaRequest); listener.process(sevaRequest); verify(complaintRepository).save(enrichedSevaRequest); }
|
### Question:
ActionRepository { public boolean checkActionNameExit(String actionName) { String Query = ActionQueryBuilder.checkActionNameExit(); final Map<String, Object> parametersMap = new HashMap<String, Object>(); parametersMap.put("name", actionName); SqlRowSet sqlRowSet = namedParameterJdbcTemplate.queryForRowSet(Query, parametersMap); if (sqlRowSet.next() && sqlRowSet.getLong("id") > 0) { return true; } return false; } List<Action> createAction(final ActionRequest actionRequest); List<Action> updateAction(final ActionRequest actionRequest); boolean checkActionNameExit(String actionName); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); ActionService getAllActionsBasedOnRoles(ActionRequest actionRequest); List<Action> getAllActions(ActionRequest actionRequest); List<Action> getAllMDMSActions(ActionRequest actionRequest); static RequestInfo getRInfo(); static final Logger LOGGER; }### Answer:
@Test @Sql(scripts = { "/sql/clearAction.sql", "/sql/insertActionData.sql" }) public void TestCheckActionNameExit() { boolean exist = actionRepository.checkActionNameExit("Get all ReceivingMode"); assertThat(exist == true); }
@Test @Sql(scripts = { "/sql/clearAction.sql", "/sql/insertActionData.sql" }) public void TestCheckActionNameDoesNotExit() { boolean exist = actionRepository.checkActionNameExit("TestActionName"); assertThat(exist == false); }
|
### Question:
ActionRepository { public boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams) { String Query = ActionQueryBuilder.checkCombinationOfUrlAndqueryparamsExist(); final Map<String, Object> parametersMap = new HashMap<String, Object>(); parametersMap.put("url", url); parametersMap.put("queryparams", queryParams); SqlRowSet sqlRowSet = namedParameterJdbcTemplate.queryForRowSet(Query, parametersMap); if (sqlRowSet.next() && sqlRowSet.getLong("id") > 0) { return true; } return false; } List<Action> createAction(final ActionRequest actionRequest); List<Action> updateAction(final ActionRequest actionRequest); boolean checkActionNameExit(String actionName); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); ActionService getAllActionsBasedOnRoles(ActionRequest actionRequest); List<Action> getAllActions(ActionRequest actionRequest); List<Action> getAllMDMSActions(ActionRequest actionRequest); static RequestInfo getRInfo(); static final Logger LOGGER; }### Answer:
@Test @Sql(scripts = { "/sql/clearAction.sql", "/sql/insertActionData.sql" }) public void TestCheckCombinationOfUrlAndqueryparamsExist() { boolean exist = actionRepository.checkCombinationOfUrlAndqueryparamsExist("/pgr/receivingmode", "tenantId="); assertThat(exist == true); }
@Test @Sql(scripts = { "/sql/clearAction.sql", "/sql/insertActionData.sql" }) public void TestCheckCombinationOfUrlAndqueryparamsNotExist() { boolean exist = actionRepository.checkCombinationOfUrlAndqueryparamsExist("/test/testreceivingmode", "test="); assertThat(exist == false); }
|
### Question:
ActionRepository { public ActionService getAllActionsBasedOnRoles(ActionRequest actionRequest) { ActionService service = new ActionService(); service.setModules(new ArrayList<Module>()); List<Module> moduleList = null; List<Module> allServiceList = null; Map<String, List<Action>> actionMap = getActionsQueryBuilder(actionRequest); if (actionMap.size() > 0) { moduleList = getServiceQueryBuilder(actionRequest, actionMap); } if (moduleList != null && moduleList.size() > 0) { allServiceList = getAllServicesQueryBuilder(actionRequest, moduleList); } if (allServiceList != null && allServiceList.size() > 0) { List<Module> rootModules = prepareListOfRootModules(allServiceList, actionMap); for (Module module : rootModules) { getSubmodule(module, allServiceList, actionMap); } removeMainModuleDoesnotExistActions(rootModules); service.setModules(rootModules); } return service; } List<Action> createAction(final ActionRequest actionRequest); List<Action> updateAction(final ActionRequest actionRequest); boolean checkActionNameExit(String actionName); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); ActionService getAllActionsBasedOnRoles(ActionRequest actionRequest); List<Action> getAllActions(ActionRequest actionRequest); List<Action> getAllMDMSActions(ActionRequest actionRequest); static RequestInfo getRInfo(); static final Logger LOGGER; }### Answer:
@Test @Sql(scripts = { "/sql/clearAction.sql", "/sql/insertActionData.sql" }) public void testShouldGetmodules() { ActionRequest actionRequest = new ActionRequest(); actionRequest.setRequestInfo(getRequestInfo()); actionRequest.setTenantId("ap.public"); List<String> roleCodes = new ArrayList<String>(); roleCodes.add("SUPERUSER"); actionRequest.setRoleCodes(roleCodes); actionRequest.setEnabled(false); List<Module> modules = actionRepository.getAllActionsBasedOnRoles(actionRequest).getModules(); assertThat(modules.size()).isEqualTo(0); }
|
### Question:
RoleRepository { public List<Role> createRole(final RoleRequest roleRequest) { LOGGER.info("Create Role Repository::" + roleRequest); final String roleInsert = RoleQueryBuilder.insertRoleQuery(); List<Role> roles = roleRequest.getRoles(); List<Map<String, Object>> batchValues = new ArrayList<>(roles.size()); for (Role role : roles) { batchValues.add(new MapSqlParameterSource("name", role.getName()).addValue("code", role.getCode()) .addValue("description", role.getDescription()) .addValue("createdby", Long.valueOf(roleRequest.getRequestInfo().getUserInfo().getId())) .addValue("createddate", new Date(new java.util.Date().getTime())) .addValue("lastmodifiedby", Long.valueOf(roleRequest.getRequestInfo().getUserInfo().getId())) .addValue("lastmodifieddate", new Date(new java.util.Date().getTime())).getValues()); } namedParameterJdbcTemplate.batchUpdate(roleInsert, batchValues.toArray(new Map[roles.size()])); return roles; } List<Role> createRole(final RoleRequest roleRequest); List<Role> updateRole(final RoleRequest roleRequest); boolean checkRoleNameDuplicationValidationErrors(String roleName); List<Role> getAllMDMSRoles(RoleSearchCriteria roleSearchCriteria); static RequestInfo getRInfo(); static final Logger LOGGER; }### Answer:
@Test @Sql(scripts = { "/sql/clearRole.sql" }) public void testshouldcreateroles() { RoleRequest roleRequest = new RoleRequest(); roleRequest.setRequestInfo(getRequestInfo()); roleRequest.setRoles(getRoles()); List<Role> roles = roleRepository.createRole(roleRequest); assertThat(roles.size()).isEqualTo(2); }
@Test @Sql(scripts = { "/sql/clearRole.sql" }) public void testRolessIfThereisNoRoles() { RoleRequest roleRequest = new RoleRequest(); List<Role> roleList = new ArrayList<Role>(); roleRequest.setRoles(roleList); List<Role> roles = roleRepository.createRole(roleRequest); assertThat(roles.size()).isEqualTo(0); }
|
### Question:
BoundaryRepository { public Boundary fetchBoundaryById(Long id, String tenantId) { String url = this.boundaryServiceHost + "egov-location/boundarys?boundary.id={id}&boundary.tenantId={tenantId}"; return getBoundaryServiceResponse(url, id, tenantId).getBoundaries().get(0); } BoundaryRepository(RestTemplate restTemplate,
@Value("${egov.services.boundary.host}") String boundaryServiceHost); Boundary fetchBoundaryById(Long id, String tenantId); }### Answer:
@Test public void test_should_fetch_boundary_for_given_id() throws Exception { server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(new Resources().getFileContents("successBoundaryResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final Boundary boundary = boundaryRepository.fetchBoundaryById(1L,"ap.public"); server.verify(); assertEquals(Long.valueOf(1), boundary.getId()); assertEquals("Kurnool", boundary.getName()); }
|
### Question:
RoleRepository { public List<Role> updateRole(final RoleRequest roleRequest) { LOGGER.info("update Role Repository::" + roleRequest); final String roleUpdate = RoleQueryBuilder.updateRoleQuery(); List<Role> roles = roleRequest.getRoles(); List<Map<String, Object>> batchValues = new ArrayList<>(roles.size()); for (Role role : roles) { batchValues.add(new MapSqlParameterSource("name", role.getName()).addValue("code", role.getCode()) .addValue("description", role.getDescription()) .addValue("lastmodifiedby", Long.valueOf(roleRequest.getRequestInfo().getUserInfo().getId())) .addValue("lastmodifieddate", new Date(new java.util.Date().getTime())).getValues()); } namedParameterJdbcTemplate.batchUpdate(roleUpdate, batchValues.toArray(new Map[roles.size()])); return roles; } List<Role> createRole(final RoleRequest roleRequest); List<Role> updateRole(final RoleRequest roleRequest); boolean checkRoleNameDuplicationValidationErrors(String roleName); List<Role> getAllMDMSRoles(RoleSearchCriteria roleSearchCriteria); static RequestInfo getRInfo(); static final Logger LOGGER; }### Answer:
@Test @Sql(scripts = { "/sql/clearRole.sql", "/sql/insertRoleData.sql" }) public void testShouldUpdateRoles() { RoleRequest roleRequest = new RoleRequest(); roleRequest.setRequestInfo(getRequestInfo()); List<Role> roleList = new ArrayList<Role>(); Role role = Role.builder().id(1L).name("Citizen").code("citizencode").description("citizendescription").build(); roleList.add(role); roleRequest.setRoles(roleList); List<Role> roles = roleRepository.updateRole(roleRequest); assertThat(roles.size()).isEqualTo(1); assertThat(roles.get(0).getCode().equals("citizencode")); assertThat(roles.get(0).getDescription().equals("citizendescription")); }
|
### Question:
RoleRepository { public boolean checkRoleNameDuplicationValidationErrors(String roleName) { final String query = RoleQueryBuilder.checkRoleNameDuplicationValidationErrors(); final Map<String, Object> parametersMap = new HashMap<String, Object>(); parametersMap.put("name", roleName); SqlRowSet sqlRowSet = namedParameterJdbcTemplate.queryForRowSet(query, parametersMap); if (sqlRowSet != null && sqlRowSet.next() && sqlRowSet.getString("code") != null && sqlRowSet.getString("code") != "") { return true; } return false; } List<Role> createRole(final RoleRequest roleRequest); List<Role> updateRole(final RoleRequest roleRequest); boolean checkRoleNameDuplicationValidationErrors(String roleName); List<Role> getAllMDMSRoles(RoleSearchCriteria roleSearchCriteria); static RequestInfo getRInfo(); static final Logger LOGGER; }### Answer:
@Test @Sql(scripts = { "/sql/clearRole.sql", "/sql/insertRoleData.sql" }) public void testCheckRoleNameDuplicationValidationExist() { boolean exist = roleRepository.checkRoleNameDuplicationValidationErrors("SUPERUSER"); assertThat(exist == true); }
@Test @Sql(scripts = { "/sql/clearRole.sql", "/sql/insertRoleData.sql" }) public void testCheckRoleNameDuplicationValidationErrors() { boolean exist = roleRepository.checkRoleNameDuplicationValidationErrors("Super User"); assertThat(exist == false); }
|
### Question:
EmployeeRepository { public Employee fetchEmployeeByPositionId(final Long positionId, final LocalDate asOnDate, final String tenantId) { RequestInfoWrapper wrapper = RequestInfoWrapper.builder().RequestInfo(RequestInfo.builder().build()).build(); final String date = asOnDate.toString("dd/MM/yyyy"); final EmployeeResponse employeeResponse = restTemplate .postForObject(hrMasterPositionUrl, wrapper, EmployeeResponse.class, positionId, date, tenantId); return employeeResponse.getEmployees().get(0); } EmployeeRepository(RestTemplate restTemplate,
@Value("${egov.services.hremployee.host}") String employeeServiceHost,
@Value("${egov.services.hr_employee.positionhierarchys}") String hrMasterHost); Employee fetchEmployeeByPositionId(final Long positionId, final LocalDate asOnDate, final String tenantId); }### Answer:
@Test public void test_should_fetch_employee_for_given_positionid() throws Exception { LocalDate sysDate = new LocalDate(); server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(new Resources().getFileContents("successEmployeeResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final Employee employee = employeeRepository.fetchEmployeeByPositionId(1L, sysDate, "1"); server.verify(); assertEquals(Long.valueOf(1), employee.getId()); assertEquals("narasappa", employee.getName()); }
|
### Question:
RoleService { public List<Role> getRoles(RoleSearchCriteria roleSearchCriteria) { RoleFinderQueryBuilder queryBuilder = new RoleFinderQueryBuilder(roleSearchCriteria); return (List<Role>) (List<?>) repository.run(queryBuilder, new RoleRowMapper()); } @Autowired RoleService(BaseRepository repository, RoleRepository roleRepository); List<Role> getRoles(RoleSearchCriteria roleSearchCriteria); List<Role> getRolesfromMDMS(RoleSearchCriteria roleSearchCriteria); List<Role> createRole(RoleRequest roleRequest); List<Role> updateRole(RoleRequest roleRequest); boolean checkRoleNameDuplicationValidationErrors(String roleName); }### Answer:
@Test public void testShouldReturnRolesForCodes() throws Exception { RoleSearchCriteria roleSearchCriteria = RoleSearchCriteria.builder().build(); List<Object> expectedRoles = getRoles(); when(repository.run(Mockito.any(RoleFinderQueryBuilder.class), Mockito.any(RoleRowMapper.class))) .thenReturn(expectedRoles); List<Role> actualActions = roleService.getRoles(roleSearchCriteria); assertEquals(expectedRoles, actualActions); }
|
### Question:
RoleActionService { public List<RoleAction> createRoleActions(final RoleActionsRequest rolActionRequest) { return roleActionRepository.createRoleActions(rolActionRequest); } @Autowired RoleActionService(RoleActionRepository roleActionRepository); List<RoleAction> createRoleActions(final RoleActionsRequest rolActionRequest); boolean checkActionNamesAreExistOrNot(final RoleActionsRequest roleActionRequest); boolean addUniqueValidationForTenantAndRoleAndAction(final RoleActionsRequest rolActionRequest); }### Answer:
@Test public void testShoudCreateRoleActions() { List<RoleAction> roleActions = new ArrayList<RoleAction>(); RoleAction action = new RoleAction(); action.setRoleCode("CITIZEN"); action.setActionId(1); action.setTenantId("default"); roleActions.add(action); RoleAction action1 = new RoleAction(); action1.setRoleCode("CITIZEN"); action1.setActionId(2); action1.setTenantId("default"); roleActions.add(action); RoleActionsRequest roleRequest = new RoleActionsRequest(); when(roleActionRepository.createRoleActions(any(RoleActionsRequest.class))).thenReturn(roleActions); List<RoleAction> rolesList = roleActionService.createRoleActions(roleRequest); assertThat(rolesList).isEqualTo(roleActions); }
|
### Question:
RoleActionService { public boolean checkActionNamesAreExistOrNot(final RoleActionsRequest roleActionRequest) { return roleActionRepository.checkActionNamesAreExistOrNot(roleActionRequest); } @Autowired RoleActionService(RoleActionRepository roleActionRepository); List<RoleAction> createRoleActions(final RoleActionsRequest rolActionRequest); boolean checkActionNamesAreExistOrNot(final RoleActionsRequest roleActionRequest); boolean addUniqueValidationForTenantAndRoleAndAction(final RoleActionsRequest rolActionRequest); }### Answer:
@Test public void testcheckActionNamesAreExistOrNot() { when(roleActionRepository.checkActionNamesAreExistOrNot(any(RoleActionsRequest.class))).thenReturn(false); boolean exist = roleActionService.checkActionNamesAreExistOrNot(any(RoleActionsRequest.class)); assertThat(exist == false); }
|
### Question:
RoleActionService { public boolean addUniqueValidationForTenantAndRoleAndAction(final RoleActionsRequest rolActionRequest) { return roleActionRepository.addUniqueValidationForTenantAndRoleAndAction(rolActionRequest); } @Autowired RoleActionService(RoleActionRepository roleActionRepository); List<RoleAction> createRoleActions(final RoleActionsRequest rolActionRequest); boolean checkActionNamesAreExistOrNot(final RoleActionsRequest roleActionRequest); boolean addUniqueValidationForTenantAndRoleAndAction(final RoleActionsRequest rolActionRequest); }### Answer:
@Test public void TestAddUniqueValidationForTenantAndRoleAndAction() { when(roleActionRepository.addUniqueValidationForTenantAndRoleAndAction(any(RoleActionsRequest.class))) .thenReturn(false); boolean exist = roleActionService.addUniqueValidationForTenantAndRoleAndAction(any(RoleActionsRequest.class)); assertThat(exist == false); }
|
### Question:
ActionService { public List<Action> getActions(ActionSearchCriteria actionSearchCriteria) { ActionFinderQueryBuilder queryBuilder = new ActionFinderQueryBuilder(actionSearchCriteria); return (List<Action>) (List<?>) repository.run(queryBuilder, new ActionRowMapper()); } @Autowired ActionService(BaseRepository repository, ActionRepository actionRepository, MdmsRepository mdmsRepository); List<Action> getActions(ActionSearchCriteria actionSearchCriteria); ActionValidation validate(ValidateActionCriteria criteria); List<Action> createAction(ActionRequest actionRequest); List<Action> updateAction(ActionRequest actionRequest); boolean checkActionNameExit(String name); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); List<Module> getAllActionsBasedOnRoles(final ActionRequest actionRequest); List<Action> getAllActions(final ActionRequest actionRequest); List<Action> getAllMDMSActions(final ActionRequest actionRequest); boolean isAuthorized(AuthorizationRequest authorizeRequest); }### Answer:
@Test public void testShouldReturnActionsForUserRole() throws Exception { ActionSearchCriteria actionSearchCriteria = ActionSearchCriteria.builder().build(); List<Object> actionsExpected = getActions(); ActionFinderQueryBuilder queryBuilder = new ActionFinderQueryBuilder(actionSearchCriteria); when(repository.run(Mockito.any(ActionFinderQueryBuilder.class), Mockito.any(ActionRowMapper.class))) .thenReturn(actionsExpected); List<Action> actualActions = actionService.getActions(actionSearchCriteria); assertEquals(actionsExpected, actualActions); }
|
### Question:
ActionService { public ActionValidation validate(ValidateActionCriteria criteria) { ValidateActionQueryBuilder queryBuilder = new ValidateActionQueryBuilder(criteria); return (ActionValidation) repository.run(queryBuilder, new ActionValidationRowMapper()).get(0); } @Autowired ActionService(BaseRepository repository, ActionRepository actionRepository, MdmsRepository mdmsRepository); List<Action> getActions(ActionSearchCriteria actionSearchCriteria); ActionValidation validate(ValidateActionCriteria criteria); List<Action> createAction(ActionRequest actionRequest); List<Action> updateAction(ActionRequest actionRequest); boolean checkActionNameExit(String name); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); List<Module> getAllActionsBasedOnRoles(final ActionRequest actionRequest); List<Action> getAllActions(final ActionRequest actionRequest); List<Action> getAllMDMSActions(final ActionRequest actionRequest); boolean isAuthorized(AuthorizationRequest authorizeRequest); }### Answer:
@Test public void testValidateQueriesRepositoryToValidateTheCriteria() { ActionValidation expectedValidation = ActionValidation.builder().allowed(true).build(); when(repository.run(Mockito.any(ValidateActionQueryBuilder.class), Mockito.any(ActionValidationRowMapper.class))).thenReturn(Arrays.asList(expectedValidation)); assert (actionService.validate(ValidateActionCriteria.builder().build()).isAllowed()); }
|
### Question:
ActionService { public boolean checkActionNameExit(String name) { return actionRepository.checkActionNameExit(name); } @Autowired ActionService(BaseRepository repository, ActionRepository actionRepository, MdmsRepository mdmsRepository); List<Action> getActions(ActionSearchCriteria actionSearchCriteria); ActionValidation validate(ValidateActionCriteria criteria); List<Action> createAction(ActionRequest actionRequest); List<Action> updateAction(ActionRequest actionRequest); boolean checkActionNameExit(String name); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); List<Module> getAllActionsBasedOnRoles(final ActionRequest actionRequest); List<Action> getAllActions(final ActionRequest actionRequest); List<Action> getAllMDMSActions(final ActionRequest actionRequest); boolean isAuthorized(AuthorizationRequest authorizeRequest); }### Answer:
@Test public void testCheckActionNameExit() { when(actionRepository.checkActionNameExit("test")).thenReturn(false); Boolean exist = actionService.checkActionNameExit("test"); assertThat(exist == false); }
|
### Question:
ActionService { public boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams) { return actionRepository.checkCombinationOfUrlAndqueryparamsExist(url, queryParams); } @Autowired ActionService(BaseRepository repository, ActionRepository actionRepository, MdmsRepository mdmsRepository); List<Action> getActions(ActionSearchCriteria actionSearchCriteria); ActionValidation validate(ValidateActionCriteria criteria); List<Action> createAction(ActionRequest actionRequest); List<Action> updateAction(ActionRequest actionRequest); boolean checkActionNameExit(String name); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); List<Module> getAllActionsBasedOnRoles(final ActionRequest actionRequest); List<Action> getAllActions(final ActionRequest actionRequest); List<Action> getAllMDMSActions(final ActionRequest actionRequest); boolean isAuthorized(AuthorizationRequest authorizeRequest); }### Answer:
@Test public void testCheckCombinationOfUrlAndqueryparamsExist() { when(actionRepository.checkCombinationOfUrlAndqueryparamsExist("/test", "tenant")).thenReturn(false); Boolean exist = actionService.checkCombinationOfUrlAndqueryparamsExist("/test", "tenant"); assertThat(exist == false); }
|
### Question:
ActionService { public List<Action> getAllActions(final ActionRequest actionRequest) { return actionRepository.getAllActions(actionRequest); } @Autowired ActionService(BaseRepository repository, ActionRepository actionRepository, MdmsRepository mdmsRepository); List<Action> getActions(ActionSearchCriteria actionSearchCriteria); ActionValidation validate(ValidateActionCriteria criteria); List<Action> createAction(ActionRequest actionRequest); List<Action> updateAction(ActionRequest actionRequest); boolean checkActionNameExit(String name); boolean checkCombinationOfUrlAndqueryparamsExist(String url, String queryParams); List<Module> getAllActionsBasedOnRoles(final ActionRequest actionRequest); List<Action> getAllActions(final ActionRequest actionRequest); List<Action> getAllMDMSActions(final ActionRequest actionRequest); boolean isAuthorized(AuthorizationRequest authorizeRequest); }### Answer:
@Test public void testShouldGetModules() throws UnsupportedEncodingException, JSONException { ActionRequest actionRequest = new ActionRequest(); actionRequest.setRequestInfo(getRequestInfo()); when(actionRepository.getAllActions(actionRequest)).thenReturn(getActionList()); List<Action> actions = actionService.getAllActions(actionRequest); assertThat(getActionList().size() == actions.size()); assertThat(actions.equals(getActionList())); }
|
### Question:
TenantRepository { public Long isTenantPresent(String tenantCode) { final Map<String, Object> parameterMap = new HashMap<String, Object>() {{ put(Tenant.CODE, tenantCode); }}; SqlRowSet sqlRowSet = namedParameterJdbcTemplate.queryForRowSet(COUNT_WITH_TENANT_CODE_QUERY, parameterMap); sqlRowSet.next(); return sqlRowSet.getLong("count"); } TenantRepository(CityRepository cityRepository, NamedParameterJdbcTemplate namedParameterJdbcTemplate); List<org.egov.tenant.domain.model.Tenant> find(TenantSearchCriteria tenantSearchCriteria); @Transactional org.egov.tenant.domain.model.Tenant save(final org.egov.tenant.domain.model.Tenant tenant); @Transactional org.egov.tenant.domain.model.Tenant update(final org.egov.tenant.domain.model.Tenant tenant); Long isTenantPresent(String tenantCode); }### Answer:
@Test @Sql(scripts = {"/sql/clearCity.sql", "/sql/clearTenant.sql", "/sql/insertTenantData.sql"}) public void test_should_return_count_of_tenants_with_given_tenantCode_matching() throws Exception { Long count = tenantRepository.isTenantPresent("AP.KURNOOL"); assertThat(count).isEqualTo(1L); }
@Test @Sql(scripts = {"/sql/clearCity.sql", "/sql/clearTenant.sql", "/sql/insertTenantData.sql"}) public void test_should_return_zero_when_tenant_does_not_exist_for_the_given_tenantCode() throws Exception { Long count = tenantRepository.isTenantPresent("NON.EXISTENT"); assertThat(count).isEqualTo(0L); }
|
### Question:
ESDateTimeFormatter { public String toESDateTimeString(String date) { if (isEmpty(date)) { return null; } try { final Date inputDate = INPUT_DATE_TIME_FORMAT.parse(date); return ES_DATE_TIME_FORMAT.format(inputDate); } catch (ParseException e) { throw new RuntimeException(e); } } ESDateTimeFormatter(@Value("${app.timezone}") String timeZone); String toESDateTimeString(String date); }### Answer:
@Test public void test_should_convert_date_to_elastic_search_string_format_with_utc_timezone() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); final ESDateTimeFormatter esDateTimeFormatter = new ESDateTimeFormatter("UTC"); final String actualDateTimeString = esDateTimeFormatter.toESDateTimeString("03-12-2017 23:45:23"); assertEquals("2017-12-03T23:45:23.000+0000", actualDateTimeString); }
@Test public void test_should_return_null_when_input_date_is_null() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); final ESDateTimeFormatter esDateTimeFormatter = new ESDateTimeFormatter("UTC"); final String actualDateTimeString = esDateTimeFormatter.toESDateTimeString(null); assertNull(actualDateTimeString); }
@Test(expected = RuntimeException.class) public void test_should_throw_exception_when_input_date_is_not_of_expected_format() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); final ESDateTimeFormatter esDateTimeFormatter = new ESDateTimeFormatter("UTC"); esDateTimeFormatter.toESDateTimeString("2017/12/03 23:45:23"); }
|
### Question:
CityRepository { public City find(String tenantCode) { Map<String, Object> parameterMap = new HashMap<String, Object>() {{ put(TENANT_CODE, tenantCode); }}; return namedParameterJdbcTemplate.query(SELECT_QUERY, parameterMap, new CityRowMapper()).get(0).toDomain(); } CityRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate); City save(City city, String tenantCode); City update(City city, String tenantCode); City find(String tenantCode); }### Answer:
@Test @Sql(scripts = {"/sql/clearCity.sql", "/sql/clearTenant.sql", "/sql/insertTenantData.sql", "/sql/insertCityData.sql", "/sql/updateCityData.sql"}) public void test_should_retrieve_city() { City city = cityRepository.find("AP.KURNOOL"); Calendar calendar = Calendar.getInstance(); calendar.set(1990, Calendar.JULY, 23, 0, 0, 0); Date date = calendar.getTime(); assertThat(city.getId()).isEqualTo(1L); assertThat(city.getName()).isEqualTo("Bengaluru"); assertThat(city.getLocalName()).isEqualTo("localname"); assertThat(city.getDistrictCode()).isEqualTo("ABC"); assertThat(city.getDistrictName()).isEqualTo("Udupi"); assertThat(city.getRegionName()).isEqualTo("Region"); assertThat(city.getLongitude()).isEqualTo(34.567); assertThat(city.getLatitude()).isEqualTo(74.566); assertThat(city.getTenantCode()).isEqualTo("AP.KURNOOL"); assertThat(city.getUlbGrade()).isEqualTo("Municipality"); assertThat(city.getCreatedBy()).isEqualTo(1L); assertThat(city.getCreatedDate()).isInSameSecondAs(date); assertThat(city.getLastModifiedBy()).isEqualTo(1L); assertThat(city.getShapeFileLocation()).isEqualTo("shapeFileLocation"); assertThat(city.getCaptcha()).isEqualTo("captcha"); assertThat(city.getCode()).isEqualTo("1016"); }
|
### Question:
City { @JsonIgnore public org.egov.tenant.domain.model.City toDomain() { return org.egov.tenant.domain.model.City.builder() .name(name) .localName(localName) .districtCode(districtCode) .districtName(districtName) .ulbGrade(ulbGrade) .regionName(regionName) .longitude(longitude) .latitude(latitude) .shapeFileLocation(shapeFileLocation) .captcha(captcha) .code(code) .build(); } City(org.egov.tenant.domain.model.City city); @JsonIgnore org.egov.tenant.domain.model.City toDomain(); }### Answer:
@Test public void test_should_convert_from_contract_to_domain() { City cityContract = City.builder() .name("Bengaluru") .localName("localname") .districtCode("districtcode") .districtName("districtname") .regionName("regionname") .longitude(35.456) .latitude(75.443) .shapeFileLocation("shapeFileLocation") .captcha("captcha") .build(); org.egov.tenant.domain.model.City expectedCityModel = org.egov.tenant.domain.model.City.builder() .name("Bengaluru") .localName("localname") .districtCode("districtcode") .districtName("districtname") .regionName("regionname") .longitude(35.456) .latitude(75.443) .shapeFileLocation("shapeFileLocation") .captcha("captcha") .build(); org.egov.tenant.domain.model.City domain = cityContract.toDomain(); assertThat(domain).isEqualTo(expectedCityModel); }
|
### Question:
TenantService { public Tenant createTenant(Tenant tenant) { tenant.validate(); validateDuplicateTenant(tenant); return tenantRepository.save(tenant); } TenantService(TenantRepository tenantRepository); List<Tenant> getTenants(List<String> code, RequestInfo requestInfo); Tenant createTenant(Tenant tenant); Tenant updateTenant(Tenant tenant); }### Answer:
@Test public void test_should_save_tenant() { Tenant tenant = mock(Tenant.class); when(tenant.getCode()).thenReturn("code"); when(tenantRepository.isTenantPresent("code")).thenReturn(0L); when(tenantRepository.save(tenant)).thenReturn(tenant); Tenant result = tenantService.createTenant(tenant); assertThat(result).isEqualTo(tenant); }
@Test(expected = InvalidTenantDetailsException.class) public void test_should_throw_exception_when_tenant_is_invalid() { Tenant tenant = Tenant.builder().build(); tenantService.createTenant(tenant); verify(tenantRepository, never()).save(any(Tenant.class)); }
@Test(expected = DuplicateTenantCodeException.class) public void test_should_throw_exception_when_duplicate_tenant_code_exists() { Tenant tenant = mock(Tenant.class); when(tenant.getCode()).thenReturn("code"); when(tenantRepository.isTenantPresent("code")).thenReturn(1L); tenantService.createTenant(tenant); verify(tenantRepository, never()).save(any(Tenant.class)); }
|
### Question:
TenantService { public Tenant updateTenant(Tenant tenant) { tenant.validate(); checkTenantExist(tenant); return tenantRepository.update(tenant); } TenantService(TenantRepository tenantRepository); List<Tenant> getTenants(List<String> code, RequestInfo requestInfo); Tenant createTenant(Tenant tenant); Tenant updateTenant(Tenant tenant); }### Answer:
@Test public void test_should_update_tenant() { Tenant tenant = mock(Tenant.class); when(tenant.getCode()).thenReturn("code"); when(tenantRepository.isTenantPresent("code")).thenReturn(1L); when(tenantRepository.update(tenant)).thenReturn(tenant); Tenant result = tenantService.updateTenant(tenant); assertThat(result).isEqualTo(tenant); }
@Test(expected = InvalidTenantDetailsException.class) public void test_should_throw_exception_when_tenant_isinvalid_inupdate() { Tenant tenant = Tenant.builder().build(); tenantService.updateTenant(tenant); verify(tenantRepository, never()).update(any(Tenant.class)); }
|
### Question:
CityService { public City getCityByCityReq(CityRequest cityRequest) { City city = new City(); if (cityRequest.getCity().getId() != null) { city = (cityRepository.findByIdAndTenantId(Long.valueOf(cityRequest.getCity().getId()),cityRequest.getCity().getTenantId())); } else if (!StringUtils.isEmpty(cityRequest.getCity().getCode())) { city = (cityRepository.findByCodeAndTenantId(cityRequest.getCity().getCode(),cityRequest.getCity().getTenantId())); } return city; } @Autowired CityService(final CityRepository cityRepository); City getCityByCityReq(CityRequest cityRequest); }### Answer:
@Test public void test_should_fetch_city_for_given_id() { final org.egov.boundary.web.contract.City cityContract = org.egov.boundary.web.contract.City.builder().id("1") .code("0001").tenantId("tenantID").build(); final CityRequest cityRequestForCityId = CityRequest.builder().city(cityContract).build(); when(cityRepository.findByIdAndTenantId(Long.valueOf(cityRequestForCityId.getCity().getId()), cityRequestForCityId.getCity().getTenantId())).thenReturn(getExpectedCityDetails()); City city = cityService.getCityByCityReq(cityRequestForCityId); assertEquals("0001", city.getCode()); }
@Test public void test_should_fetch_city_for_given_code() { final org.egov.boundary.web.contract.City cityContract = org.egov.boundary.web.contract.City.builder() .code("0001").tenantId("tenantId").build(); final CityRequest cityRequestForCityCode = CityRequest.builder().city(cityContract).build(); when(cityRepository.findByCodeAndTenantId(cityRequestForCityCode.getCity().getCode(), cityRequestForCityCode.getCity().getTenantId())).thenReturn(getExpectedCityDetails()); City city = cityService.getCityByCityReq(cityRequestForCityCode); assertEquals("0001", city.getCode()); }
|
### Question:
MdmsService { public Optional<List<Geography>> fetchGeography(String tenantId, String filter, RequestInfo requestInfo) { Optional<JSONArray> geographiesCheck; List<Geography> geographies; try { geographiesCheck = mdmsRepository.getMdmsDataByCriteria(tenantId, filter, requestInfo, BoundaryConstants.GEO_MODULE_NAME, BoundaryConstants.GEO_MASTER_NAME); } catch (HttpClientErrorException e) { throw new ServiceCallException(e.getResponseBodyAsString()); } catch (RestClientException e) { throw new CustomException(GEOGRAPHY_SEARCH_MDMS_SERVICE_UNAVAILABLE_MSG, SEARCH_MDMS_SERVICE_UNAVAILABLE_DESC); } if (geographiesCheck.isPresent()) { geographies = OBJECT_MAPPER.convertValue(geographiesCheck.get(), new TypeReference<List<Geography>> () { }); geographies.forEach(geography -> geography.setTenantId(tenantId)); return Optional.of(geographies); } else return Optional.empty(); } @Autowired MdmsService(MdmsRepository mdmsRepository); Optional<List<Geography>> fetchGeography(String tenantId, String filter, RequestInfo requestInfo); Optional<Tenant> fetchTenant(String tenantId, String filter, RequestInfo requestInfo); }### Answer:
@Test public void testFetchGeography() { }
|
### Question:
BoundaryTypeService { public List<BoundaryType> getAllBoundarytypesByNameAndTenant(String name, String tenantId) { return boundaryTypeRepository.findAllByTenantIdAndName(tenantId, name); } BoundaryType createBoundaryType(BoundaryType boundaryType); BoundaryType findByIdAndTenantId(Long id, String tenantId); BoundaryType updateBoundaryType(final BoundaryType boundaryType); List<BoundaryType> getAllBoundarTypesByHierarchyTypeIdAndTenantName(final String hierarchyTypeName,
final String tenantId); BoundaryType setHierarchyLevel(final BoundaryType boundaryType, final String mode); BoundaryType getBoundaryTypeByNameAndHierarchyTypeName(final String boundaryTypename,
final String hierarchyTypeName, String tenantId); BoundaryType findByTenantIdAndCode(String tenantId, String code); List<BoundaryType> getAllBoundaryTypes(BoundaryTypeRequest boundaryTypeRequest); List<BoundaryType> getAllBoundaryTypes(BoundaryTypeSearchRequest boundarytypeRequest); List<BoundaryType> getAllBoundarytypesByNameAndTenant(String name, String tenantId); }### Answer:
@Test public void testshouldGetAllBoundaryByTenantIdAndTypeIds(){ when(boundaryTypeRepository.findAllByTenantIdAndName(any(String.class),any(String.class))) .thenReturn(getExpectedBoundaryTypeDetails()); List<Long> list = new ArrayList<Long>(); list.add(1l); list.add(2l); List<BoundaryType> boundaryTypeList = boundaryTypeService.getAllBoundarytypesByNameAndTenant("default","Test"); assertTrue(boundaryTypeList.size() == 2); assertFalse(boundaryTypeList.isEmpty()); assertTrue(boundaryTypeList != null); assertTrue(boundaryTypeList.get(0).getName().equals("City 1")); }
|
### Question:
DepartmentRepository { public DepartmentRes getDepartmentById(final Long departmentId, final String tenantId) { final RequestInfo requestInfo = RequestInfo.builder() .ts(new Date()) .build(); RequestInfoWrapper wrapper = RequestInfoWrapper.builder().RequestInfo(requestInfo).build(); return restTemplate.postForObject(departmentByIdUrl, wrapper, DepartmentRes.class, departmentId, tenantId); } @Autowired DepartmentRepository(final RestTemplate restTemplate,
@Value("${egov.services.commonmasters.host}") final String departmentServiceHostname,
@Value("${egov.services.common_masters.department}") final String departmentByIdUrl); DepartmentRes getDepartmentById(final Long departmentId, final String tenantId); }### Answer:
@Test public void test_should_return_department_by_id() { server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(new Resources().getFileContents("departmentResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final DepartmentRes departmentRes=departmentRestRepository.getDepartmentById(1L,"default"); server.verify(); assertEquals(1, departmentRes.getDepartment().size()); }
|
### Question:
DataIntegrityViolationExceptionTransformer { public void transform() { if (exception.getMessage().contains(UNIQUE_CONSTRAINT_NAME)) { throw new DuplicateMessageIdentityException(exception); } throw new MessagePersistException(exception); } DataIntegrityViolationExceptionTransformer(DataIntegrityViolationException exception); void transform(); }### Answer:
@Test(expected = DuplicateMessageIdentityException.class) public void test_should_convert_data_integrity_exception_for_unique_constraint_violation_to_domain_exception() { final String message = "ERROR: duplicate key value violates unique constraint \"unique_message_entry\""; final DataIntegrityViolationException exception = new DataIntegrityViolationException(message); new DataIntegrityViolationExceptionTransformer(exception).transform(); }
@Test(expected = MessagePersistException.class) public void test_should_convert_unknown_data_integrity_exception_to_domain_exception() { final String message = "ERROR: duplicate key value violates unique constraint \"foo\""; final DataIntegrityViolationException exception = new DataIntegrityViolationException(message); new DataIntegrityViolationExceptionTransformer(exception).transform(); }
|
### Question:
MessageRepository { public void save(List<Message> messages, AuthenticatedUser authenticatedUser) { final List<org.egov.persistence.entity.Message> entityMessages = messages.stream() .map(org.egov.persistence.entity.Message::new).collect(Collectors.toList()); setAuditFieldsForCreate(authenticatedUser, entityMessages); setUUID(entityMessages); log.info("entityMessages: "+entityMessages); try { messageJpaRepository.save(entityMessages); } catch (DataIntegrityViolationException ex) { new DataIntegrityViolationExceptionTransformer(ex).transform(); } } MessageRepository(MessageJpaRepository messageJpaRepository); List<Message> findByTenantIdAndLocale(Tenant tenant, String locale); List<Message> findAllMessage(Tenant tenant, String locale, String module, String code); void setUUID(List<org.egov.persistence.entity.Message> entityMessages); void save(List<Message> messages, AuthenticatedUser authenticatedUser); void delete(String tenant, String locale, String module, List<String> codes); void update(String tenant, String locale, String module, List<Message> domainMessages,
AuthenticatedUser authenticatedUser); void upsert(String tenant, String locale, String module, List<Message> domainMessages,
AuthenticatedUser authenticatedUser); }### Answer:
@Test public void test_should_save_messages() { List<org.egov.domain.model.Message> domainMessages = getDomainMessages(); final AuthenticatedUser user = new AuthenticatedUser(1L); messageRepository.save(domainMessages, user); verify(messageJpaRepository).save(anyListOf(Message.class)); }
|
### Question:
Tenant { public List<Tenant> getTenantHierarchy() { final ArrayList<Tenant> tenantHierarchy = new ArrayList<>(); final int tenantDepth = StringUtils.countMatches(tenantId, NAMESPACE_SEPARATOR); tenantHierarchy.add(new Tenant(tenantId)); for (int index = tenantDepth; index >= 1; index--) { final String tenant = tenantId.substring(0, StringUtils.ordinalIndexOf(tenantId, NAMESPACE_SEPARATOR, index)); tenantHierarchy.add(new Tenant(tenant)); } tenantHierarchy.add(new Tenant(DEFAULT_TENANT)); return tenantHierarchy; } List<Tenant> getTenantHierarchy(); boolean isDefaultTenant(); boolean isMoreSpecificComparedTo(Tenant otherTenant); static final String DEFAULT_TENANT; }### Answer:
@Test public void test_should_split_name_spaced_tenant_code_to_hierarchy_list() { final Tenant tenant = new Tenant("a.b.c.d"); final List<Tenant> tenantHierarchyList = tenant.getTenantHierarchy(); assertEquals(5, tenantHierarchyList.size()); assertEquals(new Tenant("a.b.c.d"), tenantHierarchyList.get(0)); assertEquals(new Tenant("a.b.c"), tenantHierarchyList.get(1)); assertEquals(new Tenant("a.b"), tenantHierarchyList.get(2)); assertEquals(new Tenant("a"), tenantHierarchyList.get(3)); assertEquals(new Tenant("default"), tenantHierarchyList.get(4)); }
@Test public void test_should_return_default_tenant_along_with_tenant_id_when_namespace_not_present() { final Tenant tenant = new Tenant("a"); final List<Tenant> tenantHierarchyList = tenant.getTenantHierarchy(); assertEquals(2, tenantHierarchyList.size()); assertEquals(new Tenant("a"), tenantHierarchyList.get(0)); assertEquals(new Tenant("default"), tenantHierarchyList.get(1)); }
|
### Question:
Tenant { public boolean isDefaultTenant() { return tenantId.equals(DEFAULT_TENANT); } List<Tenant> getTenantHierarchy(); boolean isDefaultTenant(); boolean isMoreSpecificComparedTo(Tenant otherTenant); static final String DEFAULT_TENANT; }### Answer:
@Test public void test_is_default_tenant_should_return_true_when_tenant_is_default() { final Tenant tenant = new Tenant("default"); assertTrue(tenant.isDefaultTenant()); }
@Test public void test_is_default_tenant_should_return_false_when_tenant_is_not_default() { final Tenant tenant = new Tenant("a.b.c"); assertFalse(tenant.isDefaultTenant()); }
|
### Question:
ServiceTypeRepository { public ServiceType fetchServiceTypeByCode(String serviceCode, String tenantId) { String url = this.complaintTypeServiceHostname + SERVICE_TYPE_BY_CODE_URL; return getComplaintTypeServiceResponse(url, serviceCode, tenantId).getComplaintTypes().get(0); } ServiceTypeRepository(RestTemplate restTemplate,
@Value("${egov.services.pgrrest.host}") String complaintTypeServiceHostname); ServiceType fetchServiceTypeByCode(String serviceCode, String tenantId); }### Answer:
@Test public void test_should_fetch_complainttype_for_given_code() throws Exception { server.expect(once(), requestTo("http: .andRespond(withSuccess(new Resources().getFileContents("successComplaintTypeResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final ServiceType complaintType = complaintTypeRepository.fetchServiceTypeByCode("AOS","ap.public"); server.verify(); assertEquals("10", complaintType.getSlaHours().toString()); }
|
### Question:
ReportService { public ResponseEntity<?> getSuccessResponse(final MetadataResponse metadataResponse, final RequestInfo requestInfo, String tenantID) { final MetadataResponse metadataResponses = new MetadataResponse(); final ResponseInfo responseInfo = responseInfoFactory.createResponseInfoFromRequestInfo(requestInfo, true); responseInfo.setStatus(HttpStatus.OK.toString()); metadataResponses.setRequestInfo(responseInfo); metadataResponses.setTenantId(tenantID); metadataResponses.setReportDetails(metadataResponse.getReportDetails()); return new ResponseEntity<>(metadataResponses, HttpStatus.OK); } MetadataResponse getMetaData(MetaDataRequest metaDataRequest, String moduleName); ResponseEntity<?> getSuccessResponse(final MetadataResponse metadataResponse, final RequestInfo requestInfo,
String tenantID); ResponseEntity<?> getReportDataSuccessResponse(final List<ReportResponse> reportResponse, final RequestInfo requestInfo
,String tenantId); ResponseEntity<?> getFailureResponse( final RequestInfo requestInfo,
String tenantID); ResponseEntity<?> getFailureResponse( final RequestInfo requestInfo,
String tenantID, Exception e); ResponseEntity<?> reloadResponse( final RequestInfo requestInfo, Exception e); List<ReportResponse> getAllReportData(ReportRequest reportRequest,String moduleName,String authToken); ReportResponse getReportData(ReportRequest reportRequest,String moduleName,String reportName,String authToken); static final Logger LOGGER; }### Answer:
@Test public void testGetSuccessResponse() { }
|
### Question:
Tenant { public boolean isMoreSpecificComparedTo(Tenant otherTenant) { if (tenantId.equals(otherTenant.getTenantId())) { return false; } else if (otherTenant.isDefaultTenant()) { return true; } return tenantId.indexOf(otherTenant.getTenantId()) == 0; } List<Tenant> getTenantHierarchy(); boolean isDefaultTenant(); boolean isMoreSpecificComparedTo(Tenant otherTenant); static final String DEFAULT_TENANT; }### Answer:
@Test public void test_is_more_specific_compared_to_should_return_false_when_other_tenant_has_same_id() { final Tenant tenant = new Tenant("a.b.c"); assertFalse(tenant.isMoreSpecificComparedTo(new Tenant("a.b.c"))); }
@Test public void test_is_more_specific_compared_to_should_return_false_when_other_tenant_is_more_specific_in_hierarchy() { final Tenant tenant = new Tenant("a.b.c"); assertFalse(tenant.isMoreSpecificComparedTo(new Tenant("a.b.c.d"))); }
@Test public void test_is_more_specific_compared_to_should_return_false_when_other_tenant_is_of_different_hierarchy() { final Tenant tenant = new Tenant("a.b.c"); assertFalse(tenant.isMoreSpecificComparedTo(new Tenant("d.e"))); }
@Test public void test_is_more_specific_compared_to_should_return_true_when_other_tenant_is_less_specific_in_hierarchy() { final Tenant tenant = new Tenant("a.b.c.d"); assertTrue(tenant.isMoreSpecificComparedTo(new Tenant("a.b"))); }
|
### Question:
Message { public boolean isMoreSpecificComparedTo(Message otherMessage) { final Tenant otherTenant = otherMessage.getMessageIdentity().getTenant(); return messageIdentity.getTenant().isMoreSpecificComparedTo(otherTenant); } boolean isMoreSpecificComparedTo(Message otherMessage); String getCode(); String getModule(); String getLocale(); String getTenant(); }### Answer:
@Test public void test_should_return_true_when_given_tenant_is_more_specific_than_other_tenant() { final MessageIdentity messageIdentity1 = MessageIdentity.builder() .locale("en_IN") .module("module") .code("code1") .tenant(new Tenant("mh.panvel")) .build(); final Message message1 = Message.builder() .message("mh.panvel message") .messageIdentity(messageIdentity1) .build(); final MessageIdentity messageIdentity2 = MessageIdentity.builder() .locale("en_IN") .module("module") .code("code1") .tenant(new Tenant("mh")) .build(); final Message message2 = Message.builder() .message("mh message") .messageIdentity(messageIdentity2) .build(); assertTrue(message1.isMoreSpecificComparedTo(message2)); }
@Test public void test_should_return_false_when_given_tenant_is_less_specific_than_other_tenant() { final MessageIdentity messageIdentity1 = MessageIdentity.builder() .locale("en_IN") .module("module") .code("code1") .tenant(new Tenant("mh.panvel")) .build(); final Message message1 = Message.builder() .message("mh.panvel message") .messageIdentity(messageIdentity1) .build(); final MessageIdentity messageIdentity2 = MessageIdentity.builder() .locale("en_IN") .module("module") .code("code1") .tenant(new Tenant("mh")) .build(); final Message message2 = Message.builder() .message("mh message") .messageIdentity(messageIdentity2) .build(); assertFalse(message2.isMoreSpecificComparedTo(message1)); }
|
### Question:
MessageService { public void updateMessagesForModule(Tenant tenant, List<Message> messages, AuthenticatedUser user) { if (CollectionUtils.isEmpty(messages)) { throw new IllegalArgumentException("update message list cannot be empty"); } final Message message = messages.get(0); messageRepository.update(message.getTenant(), message.getLocale(), message.getModule(), messages, user); bustCacheEntriesForMessages(tenant, messages); } MessageService(MessageRepository messageRepository, MessageCacheRepository messageCacheRepository); void upsert(Tenant tenant, List<Message> messages, AuthenticatedUser user); void create(Tenant tenant, List<Message> messages, AuthenticatedUser user); void updateMessagesForModule(Tenant tenant, List<Message> messages, AuthenticatedUser user); void bustCache(); List<Message> getFilteredMessages(MessageSearchCriteria searchCriteria); void delete(List<MessageIdentity> messageIdentities); }### Answer:
@Test public void test_should_update_messages() { final Tenant tenant = new Tenant(TENANT_ID); final String module = "module"; final AuthenticatedUser user = new AuthenticatedUser(1L); final MessageIdentity messageIdentity1 = MessageIdentity.builder() .code("core.msg.OTPvalidated") .locale(MR_IN) .module(module) .tenant(tenant) .build(); Message message1 = Message.builder() .messageIdentity(messageIdentity1) .message("OTP यशस्वीपणे प्रमाणित") .build(); final MessageIdentity messageIdentity2 = MessageIdentity.builder() .code("core.lbl.imageupload") .locale(MR_IN) .module(module) .tenant(tenant) .build(); Message message2 = Message.builder() .messageIdentity(messageIdentity2) .message("प्रतिमा यशस्वीरित्या अपलोड") .build(); List<Message> modelMessages = Arrays.asList(message1, message2); messageService.updateMessagesForModule(tenant, modelMessages, user); verify(messageRepository).update(TENANT_ID, MR_IN, module, modelMessages, user); }
|
### Question:
MessageService { public void delete(List<MessageIdentity> messageIdentities) { final Map<Tenant, List<MessageIdentity>> tenantToMessageIdentitiesMap = messageIdentities.stream() .collect(Collectors.groupingBy(MessageIdentity::getTenant)); tenantToMessageIdentitiesMap.keySet() .forEach(tenant -> deleteMessagesForGivenTenant(tenantToMessageIdentitiesMap, tenant)); } MessageService(MessageRepository messageRepository, MessageCacheRepository messageCacheRepository); void upsert(Tenant tenant, List<Message> messages, AuthenticatedUser user); void create(Tenant tenant, List<Message> messages, AuthenticatedUser user); void updateMessagesForModule(Tenant tenant, List<Message> messages, AuthenticatedUser user); void bustCache(); List<Message> getFilteredMessages(MessageSearchCriteria searchCriteria); void delete(List<MessageIdentity> messageIdentities); }### Answer:
@Test public void test_should_delete_messages() { final MessageIdentity messageIdentity1 = MessageIdentity.builder() .code("code1") .locale(MR_IN) .module("module1") .tenant(new Tenant("tenant1")) .build(); final MessageIdentity messageIdentity2 = MessageIdentity.builder() .code("code2") .locale(ENGLISH_INDIA) .module("module2") .tenant(new Tenant("tenant1")) .build(); final MessageIdentity messageIdentity3 = MessageIdentity.builder() .code("code3") .locale(ENGLISH_INDIA) .module("module3") .tenant(new Tenant("tenant2")) .build(); List<MessageIdentity> messageIdentities = Arrays.asList(messageIdentity1, messageIdentity2, messageIdentity3); messageService.delete(messageIdentities); verify(messageRepository, times(1)) .delete("tenant1", MR_IN, "module1", Collections.singletonList("code1")); verify(messageRepository, times(1)) .delete("tenant1", ENGLISH_INDIA, "module2", Collections.singletonList("code2")); verify(messageRepository, times(1)) .delete("tenant2", ENGLISH_INDIA, "module3", Collections.singletonList("code3")); }
|
### Question:
MeterStatusService { public List<MeterStatus> pushCreateToQueue(final MeterStatusReq meterStatusReq) { logger.info("MeterStatusRequest :" + meterStatusReq); return meterStatusRepository.pushCreateToQueue(meterStatusReq); } List<MeterStatus> pushCreateToQueue(final MeterStatusReq meterStatusReq); MeterStatusReq create(final MeterStatusReq meterStatusRequest); List<MeterStatus> pushUpdateToQueue(final MeterStatusReq meterStatusRequest); MeterStatusReq update(final MeterStatusReq meterStatusRequest); List<MeterStatus> getMeterStatus(final MeterStatusGetRequest meterStatusGetRequest); static final Logger logger; }### Answer:
@Test public void test_should_push_createMeterStatusRequest_to_queue() { when(meterStatusRepository.pushCreateToQueue(getMeterStatusRequest())).thenReturn(getListOfMeterStatuses()); assertTrue(getListOfMeterStatuses().equals(meterStatusService.pushCreateToQueue(getMeterStatusRequest()))); }
|
### Question:
MeterStatusService { public List<MeterStatus> pushUpdateToQueue(final MeterStatusReq meterStatusRequest) { logger.info("MeterStatusRequest :" + meterStatusRequest); return meterStatusRepository.pushUpdateToQueue(meterStatusRequest); } List<MeterStatus> pushCreateToQueue(final MeterStatusReq meterStatusReq); MeterStatusReq create(final MeterStatusReq meterStatusRequest); List<MeterStatus> pushUpdateToQueue(final MeterStatusReq meterStatusRequest); MeterStatusReq update(final MeterStatusReq meterStatusRequest); List<MeterStatus> getMeterStatus(final MeterStatusGetRequest meterStatusGetRequest); static final Logger logger; }### Answer:
@Test public void test_should_push_updateMeterStatusRequest_to_queue() { when(meterStatusRepository.pushUpdateToQueue(getMeterStatusRequestForUpdate())) .thenReturn(getListOfMeterStatusesForUpdate()); assertTrue(getListOfMeterStatusesForUpdate() .equals(meterStatusService.pushUpdateToQueue(getMeterStatusRequestForUpdate()))); }
|
### Question:
MeterStatusService { public MeterStatusReq create(final MeterStatusReq meterStatusRequest) { return meterStatusRepository.create(meterStatusRequest); } List<MeterStatus> pushCreateToQueue(final MeterStatusReq meterStatusReq); MeterStatusReq create(final MeterStatusReq meterStatusRequest); List<MeterStatus> pushUpdateToQueue(final MeterStatusReq meterStatusRequest); MeterStatusReq update(final MeterStatusReq meterStatusRequest); List<MeterStatus> getMeterStatus(final MeterStatusGetRequest meterStatusGetRequest); static final Logger logger; }### Answer:
@Test public void test_should_create_meterStatusRequest_and_persist_to_db() { when(meterStatusRepository.create(getMeterStatusRequest())).thenReturn(getMeterStatusRequest()); assertTrue(getMeterStatusRequest().equals(meterStatusService.create(getMeterStatusRequest()))); }
|
### Question:
MeterStatusService { public MeterStatusReq update(final MeterStatusReq meterStatusRequest) { return meterStatusRepository.update(meterStatusRequest); } List<MeterStatus> pushCreateToQueue(final MeterStatusReq meterStatusReq); MeterStatusReq create(final MeterStatusReq meterStatusRequest); List<MeterStatus> pushUpdateToQueue(final MeterStatusReq meterStatusRequest); MeterStatusReq update(final MeterStatusReq meterStatusRequest); List<MeterStatus> getMeterStatus(final MeterStatusGetRequest meterStatusGetRequest); static final Logger logger; }### Answer:
@Test public void test_should_update_meterStatusRequest_and_persist_to_db() { when(meterStatusRepository.update(getMeterStatusRequestForUpdate())) .thenReturn(getMeterStatusRequestForUpdate()); assertTrue( getMeterStatusRequestForUpdate().equals(meterStatusService.update(getMeterStatusRequestForUpdate()))); }
|
### Question:
MeterStatusService { public List<MeterStatus> getMeterStatus(final MeterStatusGetRequest meterStatusGetRequest) { return meterStatusRepository.getMeterStatusByCriteria(meterStatusGetRequest); } List<MeterStatus> pushCreateToQueue(final MeterStatusReq meterStatusReq); MeterStatusReq create(final MeterStatusReq meterStatusRequest); List<MeterStatus> pushUpdateToQueue(final MeterStatusReq meterStatusRequest); MeterStatusReq update(final MeterStatusReq meterStatusRequest); List<MeterStatus> getMeterStatus(final MeterStatusGetRequest meterStatusGetRequest); static final Logger logger; }### Answer:
@Test public void test_should_be_able_to_search_meterStatus_as_per_criteria() { when(meterStatusRepository.getMeterStatusByCriteria(getMeterStatusGetRequest())).thenReturn(getListOfMeterStatuses()); assertTrue(getListOfMeterStatuses().equals(meterStatusService.getMeterStatus(getMeterStatusGetRequest()))); }
|
### Question:
GapcodeService { public List<Gapcode> getGapcodes(final GapcodeGetRequest gapcodeGetRequest) { return gapcodeRepository.findForCriteria(gapcodeGetRequest); } List<Gapcode> pushCreateToQueue(final String topic, final String key,
final GapcodeRequest gapcodeRequest); GapcodeRequest create(final GapcodeRequest gapcodeRequest); List<Gapcode> pushUpdateToQueue(final String topic, final String key,
final GapcodeRequest gapcodeRequest); GapcodeRequest update(final GapcodeRequest gapcodeRequest); List<Gapcode> getGapcodes(final GapcodeGetRequest gapcodeGetRequest); List<CommonDataModel> getFormulaQuery(); }### Answer:
@Test public void test_Search_For_Gapcode() { final List<Gapcode> gapcodeList = new ArrayList<>(); final Gapcode gapcode = Mockito.mock(Gapcode.class); gapcodeList.add(gapcode); when(gapcodeRepository.findForCriteria(any(GapcodeGetRequest.class))) .thenReturn(gapcodeList); assertTrue(gapcodeList.equals(gapcodeService .getGapcodes(any(GapcodeGetRequest.class)))); }
@Test public void test_Search_For_Gapcode_Notnull() { final List<Gapcode> gapcodeList = new ArrayList<>(); final Gapcode gapcode = Mockito.mock(Gapcode.class); gapcodeList.add(gapcode); when(gapcodeRepository.findForCriteria(any(GapcodeGetRequest.class))) .thenReturn(gapcodeList); assertNotNull(gapcodeService.getGapcodes(any(GapcodeGetRequest.class))); }
@Test public void test_Search_For_Gapcode_Null() { final List<Gapcode> gapcodeList = new ArrayList<>(); final Gapcode gapcode = Mockito.mock(Gapcode.class); gapcodeList.add(gapcode); when(gapcodeRepository.findForCriteria(any(GapcodeGetRequest.class))) .thenReturn(null); assertNull(gapcodeService.getGapcodes(any(GapcodeGetRequest.class))); }
|
### Question:
GapcodeService { public GapcodeRequest create(final GapcodeRequest gapcodeRequest) { return gapcodeRepository.create(gapcodeRequest); } List<Gapcode> pushCreateToQueue(final String topic, final String key,
final GapcodeRequest gapcodeRequest); GapcodeRequest create(final GapcodeRequest gapcodeRequest); List<Gapcode> pushUpdateToQueue(final String topic, final String key,
final GapcodeRequest gapcodeRequest); GapcodeRequest update(final GapcodeRequest gapcodeRequest); List<Gapcode> getGapcodes(final GapcodeGetRequest gapcodeGetRequest); List<CommonDataModel> getFormulaQuery(); }### Answer:
@Test public void test_throwException_Create_Gapcode() { final List<Gapcode> gapcodeList = new ArrayList<>(); gapcodeList.add(getGapcode()); final GapcodeRequest gapcodeRequest = new GapcodeRequest(); gapcodeRequest.setGapcode(gapcodeList); when(gapcodeRepository.create(any(GapcodeRequest.class))).thenReturn( gapcodeRequest); assertTrue(gapcodeRequest.equals(gapcodeService.create(gapcodeRequest))); }
|
### Question:
CityRepository { public City fetchCityById(Long id) { String url = this.cityServiceHost + "v1/location/city/getCitybyCityRequest"; return getCityServiceResponse(url, id).getBody().getCity(); } CityRepository(RestTemplate restTemplate, @Value("${egov.services.boundary.host}") String cityServiceHost); City fetchCityById(Long id); }### Answer:
@Test public void test_should_fetch_city_for_given_id() throws Exception { server.expect(once(), requestTo("http: .andExpect(method(HttpMethod.POST)).andRespond(withSuccess( new Resources().getFileContents("successCityResponse.json"), MediaType.APPLICATION_JSON_UTF8)); final City city = cityRepository.fetchCityById(1L); server.verify(); assertEquals("Kurnool", city.getName()); assertEquals("KC", city.getCode()); }
|
### Question:
GapcodeService { public GapcodeRequest update(final GapcodeRequest gapcodeRequest) { return gapcodeRepository.update(gapcodeRequest); } List<Gapcode> pushCreateToQueue(final String topic, final String key,
final GapcodeRequest gapcodeRequest); GapcodeRequest create(final GapcodeRequest gapcodeRequest); List<Gapcode> pushUpdateToQueue(final String topic, final String key,
final GapcodeRequest gapcodeRequest); GapcodeRequest update(final GapcodeRequest gapcodeRequest); List<Gapcode> getGapcodes(final GapcodeGetRequest gapcodeGetRequest); List<CommonDataModel> getFormulaQuery(); }### Answer:
@SuppressWarnings("unchecked") @Test(expected = Exception.class) public void test_throwException_Update_Gapcode() throws Exception { final GapcodeRequest gapcodeRequest = Mockito .mock(GapcodeRequest.class); when(gapcodeRepository.update(gapcodeRequest)).thenThrow( Exception.class); assertTrue(gapcodeRequest.equals(gapcodeService.update(gapcodeRequest))); }
|
### Question:
StorageReservoirService { public List<StorageReservoir> getStorageReservoir(final StorageReservoirGetRequest storageReservoirGetRequest) { return storageReservoirRepository.findForCriteria(storageReservoirGetRequest); } StorageReservoirRequest create(final StorageReservoirRequest storageReservoirRequest); StorageReservoirRequest update(final StorageReservoirRequest storageReservoirRequest); List<StorageReservoir> pushCreateToQueue(final String topic, final String key,
final StorageReservoirRequest storageReservoirRequest); List<StorageReservoir> pushUpdateToQueue(final String topic, final String key,
final StorageReservoirRequest storageReservoirRequest); List<StorageReservoir> getStorageReservoir(final StorageReservoirGetRequest storageReservoirGetRequest); boolean getStorageReservoirByNameAndCode(final String code, final String name, final String tenantId); }### Answer:
@SuppressWarnings("unchecked") @Test(expected = Exception.class) public void test_Should_Search_StorageReservoir() { final List<StorageReservoir> storageReservoirList = new ArrayList<>(); storageReservoirList.add(getStorageReservoir()); final StorageReservoirGetRequest storageReservoirGetRequest = Mockito.mock(StorageReservoirGetRequest.class); when(storageReservoirRepository.findForCriteria(storageReservoirGetRequest)).thenThrow(Exception.class); assertTrue( storageReservoirList.equals(storageReservoirService.getStorageReservoir(storageReservoirGetRequest))); }
|
### Question:
StorageReservoirService { public StorageReservoirRequest update(final StorageReservoirRequest storageReservoirRequest) { return storageReservoirRepository.update(storageReservoirRequest); } StorageReservoirRequest create(final StorageReservoirRequest storageReservoirRequest); StorageReservoirRequest update(final StorageReservoirRequest storageReservoirRequest); List<StorageReservoir> pushCreateToQueue(final String topic, final String key,
final StorageReservoirRequest storageReservoirRequest); List<StorageReservoir> pushUpdateToQueue(final String topic, final String key,
final StorageReservoirRequest storageReservoirRequest); List<StorageReservoir> getStorageReservoir(final StorageReservoirGetRequest storageReservoirGetRequest); boolean getStorageReservoirByNameAndCode(final String code, final String name, final String tenantId); }### Answer:
@SuppressWarnings("unchecked") @Test(expected = Exception.class) public void test_throwException_Update_StorageReservoir() throws Exception { final StorageReservoirRequest storageReservoirRequest = Mockito.mock(StorageReservoirRequest.class); when(storageReservoirRepository.update(storageReservoirRequest)) .thenThrow(Exception.class); assertTrue(storageReservoirRequest.equals(storageReservoirService.update(storageReservoirRequest))); }
|
### Question:
SourceTypeService { public List<SourceType> getWaterSourceTypes(final SourceTypeGetRequest waterSourceTypeGetRequest) { return waterSourceTypeRepository.findForCriteria(waterSourceTypeGetRequest); } SourceTypeRequest create(final SourceTypeRequest waterSourceRequest); SourceTypeRequest update(final SourceTypeRequest waterSourceRequest); List<SourceType> pushCreateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); List<SourceType> pushUpdateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); boolean getWaterSourceByNameAndCode(final String code, final String name, final String tenantId); List<SourceType> getWaterSourceTypes(final SourceTypeGetRequest waterSourceTypeGetRequest); }### Answer:
@Test public void test_Should_Search_WaterSource() { final List<SourceType> waterSourceTypes = new ArrayList<>(); waterSourceTypes.add(getWaterSourceType()); when(waterSourceTypeRepository.findForCriteria(any(SourceTypeGetRequest.class))).thenReturn(waterSourceTypes); assertTrue(waterSourceTypes.equals(waterSourceTypeService.getWaterSourceTypes(any(SourceTypeGetRequest.class)))); }
|
### Question:
SourceTypeService { public List<SourceType> pushCreateToQueue(final String topic, final String key, final SourceTypeRequest sourcetypeRequest) { for (final SourceType sourceType : sourcetypeRequest.getSourceTypes()) sourceType.setCode(codeGeneratorService.generate(SourceType.SEQ_WATERSOURCE)); try { kafkaTemplate.send(topic, key, sourcetypeRequest); } catch (final Exception ex) { log.error("Exception Encountered : " + ex); } return sourcetypeRequest.getSourceTypes(); } SourceTypeRequest create(final SourceTypeRequest waterSourceRequest); SourceTypeRequest update(final SourceTypeRequest waterSourceRequest); List<SourceType> pushCreateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); List<SourceType> pushUpdateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); boolean getWaterSourceByNameAndCode(final String code, final String name, final String tenantId); List<SourceType> getWaterSourceTypes(final SourceTypeGetRequest waterSourceTypeGetRequest); }### Answer:
@Test public void test_throwException_Push_To_Producer_WaterSource() { final List<SourceType> waterSourceList = new ArrayList<>(); waterSourceList.add(getWaterSourceType()); final SourceTypeRequest waterSourceRequest = new SourceTypeRequest(); waterSourceRequest.setSourceTypes(waterSourceList); assertTrue(waterSourceList.equals(waterSourceTypeService.pushCreateToQueue("topic", "key", waterSourceRequest))); }
|
### Question:
SourceTypeService { public SourceTypeRequest create(final SourceTypeRequest waterSourceRequest) { return waterSourceTypeRepository.create(waterSourceRequest); } SourceTypeRequest create(final SourceTypeRequest waterSourceRequest); SourceTypeRequest update(final SourceTypeRequest waterSourceRequest); List<SourceType> pushCreateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); List<SourceType> pushUpdateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); boolean getWaterSourceByNameAndCode(final String code, final String name, final String tenantId); List<SourceType> getWaterSourceTypes(final SourceTypeGetRequest waterSourceTypeGetRequest); }### Answer:
@Test public void test_throwException_Create_WaterSource() { final List<SourceType> waterSourceTypeList = new ArrayList<>(); waterSourceTypeList.add(getWaterSourceType()); final SourceTypeRequest waterSourceRequest = new SourceTypeRequest(); waterSourceRequest.setSourceTypes(waterSourceTypeList); when(waterSourceTypeRepository.create(any(SourceTypeRequest.class))) .thenReturn(waterSourceRequest); assertTrue(waterSourceRequest.equals(waterSourceTypeService.create(waterSourceRequest))); }
|
### Question:
SourceTypeService { public SourceTypeRequest update(final SourceTypeRequest waterSourceRequest) { return waterSourceTypeRepository.update(waterSourceRequest); } SourceTypeRequest create(final SourceTypeRequest waterSourceRequest); SourceTypeRequest update(final SourceTypeRequest waterSourceRequest); List<SourceType> pushCreateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); List<SourceType> pushUpdateToQueue(final String topic, final String key,
final SourceTypeRequest sourcetypeRequest); boolean getWaterSourceByNameAndCode(final String code, final String name, final String tenantId); List<SourceType> getWaterSourceTypes(final SourceTypeGetRequest waterSourceTypeGetRequest); }### Answer:
@SuppressWarnings("unchecked") @Test(expected = Exception.class) public void test_throwException_Update_WaterSource() throws Exception { final SourceTypeRequest waterSourceRequest = Mockito.mock(SourceTypeRequest.class); when(waterSourceTypeRepository.update(waterSourceRequest)).thenThrow(Exception.class); assertTrue(waterSourceRequest.equals(waterSourceTypeService.update(waterSourceRequest))); }
|
### Question:
PipeSizeService { public List<PipeSize> pushCreateToQueue(final String topic, final String key, final PipeSizeRequest pipeSizeRequest) { for (final PipeSize pipeSize : pipeSizeRequest.getPipeSizes()) { pipeSize.setCode(codeGeneratorService.generate(PipeSize.SEQ_PIPESIZE)); final double pipeSizeininch = pipeSize.getSizeInMilimeter() * 0.039370; pipeSize.setSizeInInch(Math.round(pipeSizeininch * 1000.0) / 1000.0); } try { kafkaTemplate.send(topic, key, pipeSizeRequest); } catch (final Exception ex) { log.error("Exception Encountered : " + ex); } return pipeSizeRequest.getPipeSizes(); } PipeSizeRequest create(final PipeSizeRequest pipeSizeRequest); PipeSizeRequest update(final PipeSizeRequest pipeSizeRequest); List<PipeSize> pushCreateToQueue(final String topic, final String key, final PipeSizeRequest pipeSizeRequest); List<PipeSize> pushUpdateToQueue(final String topic, final String key, final PipeSizeRequest pipeSizeRequest); boolean getPipeSizeInmmAndCode(final String code, final Double sizeInMilimeter, final String tenantId); List<PipeSize> getPipeSizes(final PipeSizeGetRequest pipeSizeGetRequest); }### Answer:
@Test public void test_Should_Create_PipeSize() throws Exception { final PipeSizeRequest pipeSizeRequest = new PipeSizeRequest(); final RequestInfo requestInfo = new RequestInfo(); final User user = new User(); user.setId(1L); requestInfo.setUserInfo(user); final List<PipeSize> pipeSizeList = new ArrayList<>(); pipeSizeList.add(getPipeSize()); pipeSizeRequest.setRequestInfo(requestInfo); pipeSizeRequest.setPipeSizes(pipeSizeList); final List<PipeSize> pipeSizeResult = pipeSizeService.pushCreateToQueue("topic", "key", pipeSizeRequest); assertNotNull(pipeSizeResult); }
|
### Question:
PipeSizeService { public List<PipeSize> pushUpdateToQueue(final String topic, final String key, final PipeSizeRequest pipeSizeRequest) { for (final PipeSize pipeSize : pipeSizeRequest.getPipeSizes()) { final double pipeSizeininch = pipeSize.getSizeInMilimeter() * 0.039370; pipeSize.setSizeInInch(Math.round(pipeSizeininch * 1000.0) / 1000.0); } try { kafkaTemplate.send(topic, key, pipeSizeRequest); } catch (final Exception ex) { log.error("Exception Encountered : " + ex); } return pipeSizeRequest.getPipeSizes(); } PipeSizeRequest create(final PipeSizeRequest pipeSizeRequest); PipeSizeRequest update(final PipeSizeRequest pipeSizeRequest); List<PipeSize> pushCreateToQueue(final String topic, final String key, final PipeSizeRequest pipeSizeRequest); List<PipeSize> pushUpdateToQueue(final String topic, final String key, final PipeSizeRequest pipeSizeRequest); boolean getPipeSizeInmmAndCode(final String code, final Double sizeInMilimeter, final String tenantId); List<PipeSize> getPipeSizes(final PipeSizeGetRequest pipeSizeGetRequest); }### Answer:
@Test public void test_Should_Update_PipeSize() throws Exception { final PipeSizeRequest pipeSizeRequest = new PipeSizeRequest(); final RequestInfo requestInfo = new RequestInfo(); final User user = new User(); user.setId(1L); requestInfo.setUserInfo(user); final List<PipeSize> pipeSizeList = new ArrayList<>(); pipeSizeList.add(getPipeSize()); pipeSizeRequest.setRequestInfo(requestInfo); pipeSizeRequest.setPipeSizes(pipeSizeList); final List<PipeSize> pipeSizeResult = pipeSizeService.pushUpdateToQueue("topic", "key", pipeSizeRequest); assertNotNull(pipeSizeResult); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.