method2testcases
stringlengths
118
3.08k
### Question: AgreementController { @GetMapping("/find-current") public RestResult<AgreementResource> findCurrent() { return agreementService.getCurrent().toGetResponse(); } @GetMapping("/find-current") RestResult<AgreementResource> findCurrent(); }### Answer: @Test public void findCurrent() throws Exception { String agreementText = "agreement text"; when(agreementServiceMock.getCurrent()).thenReturn(serviceSuccess(newAgreementResource().withText(agreementText).build())); mockMvc.perform(get("/agreement/find-current")) .andExpect(status().isOk()) .andExpect(jsonPath("$.text", is(agreementText))); }
### Question: ProjectPartnerInviteServiceImpl extends BaseTransactionalService implements ProjectPartnerInviteService { @Override @Transactional public ServiceResult<Void> deleteInvite(long inviteId) { return find(projectPartnerInviteRepository.findById(inviteId), notFoundError(ProjectPartnerInvite.class, inviteId)) .andOnSuccessReturnVoid(projectPartnerInviteRepository::delete); } @Override @Transactional ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite); @Override ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId); @Override @Transactional ServiceResult<Void> resendInvite(long inviteId); @Override @Transactional ServiceResult<Void> deleteInvite(long inviteId); @Override ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(long inviteId, long organisationId); }### Answer: @Test public void deleteInvite() { long inviteId = 2L; ProjectPartnerInvite invite = new ProjectPartnerInvite(); when(projectPartnerInviteRepository.findById(inviteId)).thenReturn(of(invite)); service.deleteInvite(inviteId); verify(projectPartnerInviteRepository).delete(invite); }
### Question: ApplicationFundingDecisionController { @PostMapping(value="/{competitionId}") public RestResult<Void> saveFundingDecisionData(@PathVariable("competitionId") final Long competitionId, @RequestBody Map<Long, FundingDecision> applicationFundingDecisions) { return applicationFundingService.saveFundingDecisionData(competitionId, applicationFundingDecisions). toPutResponse(); } @PostMapping(value="/send-notifications") RestResult<Void> sendFundingDecisions(@RequestBody FundingNotificationResource fundingNotificationResource); @PostMapping(value="/{competitionId}") RestResult<Void> saveFundingDecisionData(@PathVariable("competitionId") final Long competitionId, @RequestBody Map<Long, FundingDecision> applicationFundingDecisions); @GetMapping("/notifications-to-send") RestResult<List<FundingDecisionToSendApplicationResource>> getNotificationResourceForApplications(@RequestParam("applicationIds") List<Long> applicationIds); }### Answer: @Test public void testSaveApplicationFundingDecisionData() throws Exception { Long competitionId = 1L; Map<Long, FundingDecision> decision = asMap(1L, FundingDecision.FUNDED, 2L, FundingDecision.UNFUNDED); when(applicationFundingServiceMock.saveFundingDecisionData(competitionId, decision)).thenReturn(serviceSuccess()); mockMvc.perform(post("/applicationfunding/1") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(decision))) .andExpect(status().isOk()) .andExpect(content().string("")); verify(applicationFundingServiceMock).saveFundingDecisionData(competitionId, decision); }
### Question: ApplicationNotificationTemplateController { @GetMapping("/successful/{competitionId}") public RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId) { return applicationNotificationTemplateService.getSuccessfulNotificationTemplate(competitionId).toGetResponse(); } @GetMapping("/successful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/unsuccessful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/ineligible/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId); }### Answer: @Test public void getSuccessfulNotificationTemplate() throws Exception { Long competitionId = 1L; ApplicationNotificationTemplateResource resource = new ApplicationNotificationTemplateResource(); when(applicationNotificationTemplateService.getSuccessfulNotificationTemplate(competitionId)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/application-notification-template/successful/1") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(resource))); }
### Question: ApplicationNotificationTemplateController { @GetMapping("/unsuccessful/{competitionId}") public RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId) { return applicationNotificationTemplateService.getUnsuccessfulNotificationTemplate(competitionId).toGetResponse(); } @GetMapping("/successful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/unsuccessful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/ineligible/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId); }### Answer: @Test public void getUnsuccessfulNotificationTemplate() throws Exception { Long competitionId = 1L; ApplicationNotificationTemplateResource resource = new ApplicationNotificationTemplateResource(); when(applicationNotificationTemplateService.getUnsuccessfulNotificationTemplate(competitionId)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/application-notification-template/unsuccessful/1") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(resource))); }
### Question: ApplicationNotificationTemplateController { @GetMapping("/ineligible/{competitionId}") public RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId) { return applicationNotificationTemplateService.getIneligibleNotificationTemplate(competitionId).toGetResponse(); } @GetMapping("/successful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/unsuccessful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/ineligible/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId); }### Answer: @Test public void getIneligibleNotificationTemplate() throws Exception { long competitionId = 1L; long userId = 2L; ApplicationNotificationTemplateResource resource = new ApplicationNotificationTemplateResource(); when(applicationNotificationTemplateService.getIneligibleNotificationTemplate(competitionId)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/application-notification-template/ineligible/1") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(resource))); }
### Question: FundingDecisionMapper { public FundingDecisionStatus mapToDomain(FundingDecision source){ return FundingDecisionStatus.valueOf(source.name()); } FundingDecision mapToResource(FundingDecisionStatus source); FundingDecisionStatus mapToDomain(FundingDecision source); }### Answer: @Test public void testConvertFromResourceToDomain() { for(FundingDecision decision: FundingDecision.values()){ FundingDecisionStatus status = mapper.mapToDomain(decision); assertEquals(decision.name(), status.name()); } }
### Question: FundingDecisionMapper { public FundingDecision mapToResource(FundingDecisionStatus source){ return FundingDecision.valueOf(source.name()); } FundingDecision mapToResource(FundingDecisionStatus source); FundingDecisionStatus mapToDomain(FundingDecision source); }### Answer: @Test public void testConvertFromDomainToResource() { for(FundingDecisionStatus status: FundingDecisionStatus.values()){ FundingDecision decision = mapper.mapToResource(status); assertEquals(status.name(), decision.name()); } }
### Question: ApplicationNotificationTemplateServiceImpl extends BaseTransactionalService implements ApplicationNotificationTemplateService { @Override public ServiceResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId) { return renderTemplate(competitionId, "ineligible_application.html", (competition) -> { Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", competition.getName()); return arguments; }); } @Override ServiceResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId); }### Answer: @Test public void getIneligibleNotificationTemplate() { Competition competition = newCompetition().withName("Competition").build(); Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", competition.getName()); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(renderer.renderTemplate(eq(systemNotificationSource), any(), eq(DEFAULT_NOTIFICATION_TEMPLATES_PATH + "ineligible_application.html"), eq(arguments))) .thenReturn(serviceSuccess("MessageBody")); ServiceResult<ApplicationNotificationTemplateResource> result = service.getIneligibleNotificationTemplate(competitionId); assertTrue(result.isSuccess()); assertEquals("MessageBody", result.getSuccess().getMessageBody()); }
### Question: AffiliationController { @GetMapping("/id/{userId}/get-user-affiliations") public RestResult<AffiliationListResource> getUserAffiliations(@PathVariable("userId") long userId) { return affiliationService.getUserAffiliations(userId).toGetResponse(); } @GetMapping("/id/{userId}/get-user-affiliations") RestResult<AffiliationListResource> getUserAffiliations(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-user-affiliations") RestResult<Void> updateUserAffiliations(@PathVariable("userId") long userId, @Valid @RequestBody AffiliationListResource affiliations); }### Answer: @Test public void getUserAffiliations() throws Exception { Long userId = 1L; List<AffiliationResource> affiliations = newAffiliationResource().build(2); AffiliationListResource affiliationListResource = newAffiliationListResource() .withAffiliationList(affiliations) .build(); when(affiliationServiceMock.getUserAffiliations(userId)).thenReturn(serviceSuccess(affiliationListResource)); mockMvc.perform(get("/affiliation/id/{id}/get-user-affiliations", userId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(affiliationListResource))); verify(affiliationServiceMock, only()).getUserAffiliations(userId); }
### Question: AffiliationController { @PutMapping("/id/{userId}/update-user-affiliations") public RestResult<Void> updateUserAffiliations(@PathVariable("userId") long userId, @Valid @RequestBody AffiliationListResource affiliations) { return affiliationService.updateUserAffiliations(userId, affiliations).toPutResponse(); } @GetMapping("/id/{userId}/get-user-affiliations") RestResult<AffiliationListResource> getUserAffiliations(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-user-affiliations") RestResult<Void> updateUserAffiliations(@PathVariable("userId") long userId, @Valid @RequestBody AffiliationListResource affiliations); }### Answer: @Test public void updateUserAffiliations() throws Exception { Long userId = 1L; List<AffiliationResource> affiliations = newAffiliationResource().build(2); AffiliationListResource affiliationListResource = newAffiliationListResource() .withAffiliationList(affiliations) .build(); when(affiliationServiceMock.updateUserAffiliations(userId, affiliationListResource)).thenReturn(serviceSuccess()); mockMvc.perform(put("/affiliation/id/{id}/update-user-affiliations", userId) .contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsString(affiliationListResource))) .andExpect(status().isOk()); verify(affiliationServiceMock, only()).updateUserAffiliations(userId, affiliationListResource); }
### Question: QuestionSetupCompetitionController { @GetMapping("/get-by-id/{questionId}") public RestResult<CompetitionSetupQuestionResource> getByQuestionId(@PathVariable final long questionId) { return questionSetupCompetitionService.getByQuestionId(questionId).toGetResponse(); } @GetMapping("/get-by-id/{questionId}") RestResult<CompetitionSetupQuestionResource> getByQuestionId(@PathVariable final long questionId); @PutMapping("/save") RestResult<Void> save(@RequestBody final CompetitionSetupQuestionResource competitionSetupQuestionResource); @PostMapping("/add-default-to-competition/{competitionId}") RestResult<CompetitionSetupQuestionResource> addDefaultToCompetitionId( @PathVariable long competitionId); @PostMapping("/add-research-category-question-to-competition/{competitionId}") RestResult<Void> addResearchCategoryQuestionToCompetition(@PathVariable long competitionId); @DeleteMapping("/delete-by-id/{questionId}") RestResult<Void> deleteById(@PathVariable long questionId); @PostMapping(value = "/template-file/{questionId}", produces = "application/json") RestResult<Void> uploadTemplateFile(@RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, @PathVariable long questionId, HttpServletRequest request); @DeleteMapping(value = "/template-file/{questionId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable long questionId); }### Answer: @Test public void getByQuestionId() throws Exception { final Long questionId = 1L; when(questionSetupCompetitionServiceMock.getByQuestionId(questionId)).thenReturn(serviceSuccess(newCompetitionSetupQuestionResource().build())); mockMvc.perform(get("/question-setup/get-by-id/{questionId}", questionId)) .andExpect(status().isOk()); verify(questionSetupCompetitionServiceMock, only()).getByQuestionId(questionId); }
### Question: QuestionSetupCompetitionController { @DeleteMapping("/delete-by-id/{questionId}") public RestResult<Void> deleteById(@PathVariable long questionId) { return questionSetupCompetitionService.delete(questionId).toDeleteResponse(); } @GetMapping("/get-by-id/{questionId}") RestResult<CompetitionSetupQuestionResource> getByQuestionId(@PathVariable final long questionId); @PutMapping("/save") RestResult<Void> save(@RequestBody final CompetitionSetupQuestionResource competitionSetupQuestionResource); @PostMapping("/add-default-to-competition/{competitionId}") RestResult<CompetitionSetupQuestionResource> addDefaultToCompetitionId( @PathVariable long competitionId); @PostMapping("/add-research-category-question-to-competition/{competitionId}") RestResult<Void> addResearchCategoryQuestionToCompetition(@PathVariable long competitionId); @DeleteMapping("/delete-by-id/{questionId}") RestResult<Void> deleteById(@PathVariable long questionId); @PostMapping(value = "/template-file/{questionId}", produces = "application/json") RestResult<Void> uploadTemplateFile(@RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, @PathVariable long questionId, HttpServletRequest request); @DeleteMapping(value = "/template-file/{questionId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable long questionId); }### Answer: @Test public void deleteById() throws Exception { final long questionId = 1L; when(questionSetupCompetitionServiceMock.delete(questionId)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/question-setup/delete-by-id/{questionId}", questionId)) .andExpect(status().isNoContent()); verify(questionSetupCompetitionServiceMock, only()).delete(questionId); }
### Question: QuestionFileSetupCompetitionServiceImpl implements QuestionFileSetupCompetitionService { @Override @Transactional public ServiceResult<Void> deleteTemplateFile(long questionId) { return findFormInputByQuestionId(questionId).andOnSuccess(formInput -> { long fileId = formInput.getFile().getId(); return fileService.deleteFileIgnoreNotFound(fileId).andOnSuccessReturnVoid(() -> { formInput.setFile(null); }); }); } @Override @Transactional ServiceResult<Void> uploadTemplateFile(String contentType, String contentLength, String originalFilename, long questionId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteTemplateFile(long questionId); }### Answer: @Test public void deleteTemplateFile_submitted() throws Exception { final long questionId = 1L; final long fileId = 101L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); FormInput formInput = newFormInput() .withFile(fileEntry) .build(); when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.APPLICATION, FormInputType.TEMPLATE_DOCUMENT)).thenReturn(formInput); when(fileServiceMock.deleteFileIgnoreNotFound(fileId)).thenReturn(ServiceResult.serviceSuccess(fileEntry)); ServiceResult<Void> response = service.deleteTemplateFile(questionId); assertTrue(response.isSuccess()); assertNull(formInput.getFile()); }
### Question: QuestionSetupCompetitionServiceImpl extends BaseTransactionalService implements QuestionSetupCompetitionService { @Override @Transactional public ServiceResult<Void> delete(long questionId) { return questionSetupAddAndRemoveService.deleteQuestionInCompetition(questionId); } @Override ServiceResult<CompetitionSetupQuestionResource> getByQuestionId(long questionId); @Override @Transactional ServiceResult<CompetitionSetupQuestionResource> createByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> addResearchCategoryQuestionToCompetition(long competitionId); @Override @Transactional ServiceResult<Void> delete(long questionId); @Override @Transactional ServiceResult<CompetitionSetupQuestionResource> update(CompetitionSetupQuestionResource competitionSetupQuestionResource); }### Answer: @Test public void delete() { long questionId = 1L; when(questionSetupAddAndRemoveService.deleteQuestionInCompetition(questionId)).thenReturn(serviceSuccess()); assertTrue(service.delete(questionId).isSuccess()); }
### Question: QuestionSetupCompetitionServiceImpl extends BaseTransactionalService implements QuestionSetupCompetitionService { @Override @Transactional public ServiceResult<Void> addResearchCategoryQuestionToCompetition(long competitionId) { return find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId)) .andOnSuccess(this::saveNewResearchCategoryQuestionForCompetition) .andOnSuccessReturnVoid(); } @Override ServiceResult<CompetitionSetupQuestionResource> getByQuestionId(long questionId); @Override @Transactional ServiceResult<CompetitionSetupQuestionResource> createByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> addResearchCategoryQuestionToCompetition(long competitionId); @Override @Transactional ServiceResult<Void> delete(long questionId); @Override @Transactional ServiceResult<CompetitionSetupQuestionResource> update(CompetitionSetupQuestionResource competitionSetupQuestionResource); }### Answer: @Test public void addResearchCategoryQuestionToCompetition() { Competition competition = newCompetition().build(); Section section = newSection().build(); Question createdQuestion = newQuestion().build(); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(sectionRepository.findFirstByCompetitionIdAndName(competition.getId(), PROJECT_DETAILS.getName())) .thenReturn(section); when(questionRepository.save(createResearchCategoryQuestionExpectations(competition, section))) .thenReturn(createdQuestion); ServiceResult<Void> result = service.addResearchCategoryQuestionToCompetition(competition.getId()); assertTrue(result.isSuccess()); verify(competitionRepositoryMock).findById(competition.getId()); verify(sectionRepository).findFirstByCompetitionIdAndName(competition.getId(), PROJECT_DETAILS.getName()); verify(questionRepository).save(createResearchCategoryQuestionExpectations(competition, section)); verify(questionPriorityOrderService).prioritiseResearchCategoryQuestionAfterCreation(createdQuestion); }
### Question: QuestionSetupAddAndRemoveServiceImpl implements QuestionSetupAddAndRemoveService { @Override public ServiceResult<Question> addDefaultAssessedQuestionToCompetition(Competition competition) { if (competition == null || competitionIsNotInSetupOrReadyToOpenState(competition)) { return serviceFailure(new Error(COMPETITION_NOT_EDITABLE)); } return find(sectionRepository.findFirstByCompetitionIdAndName( competition.getId(), APPLICATION_QUESTIONS.getName()), notFoundError(Section.class) ).andOnSuccess(section -> initializeAndPersistQuestion(section, competition)); } @Override ServiceResult<Question> addDefaultAssessedQuestionToCompetition(Competition competition); @Override ServiceResult<Void> deleteQuestionInCompetition(long questionId); }### Answer: @Test public void addDefaultAssessedQuestionToCompetition_competitionIsNullShouldResultInFailure() { ServiceResult<Question> result = service.addDefaultAssessedQuestionToCompetition(null); assertTrue(result.isFailure()); } @Test public void addDefaultAssessedQuestionToCompetition_competitionIsNotInReadyOrSetupStateShouldResultInFailure() { Competition competitionInWrongState = newCompetition().withCompetitionStatus(CompetitionStatus.OPEN).build(); ServiceResult<Question> result = service.addDefaultAssessedQuestionToCompetition(competitionInWrongState); assertTrue(result.isFailure()); } @Test public void addDefaultAssessedQuestionToCompetition_sectionCannotBeFoundShouldResultInServiceFailure() { Competition competitionInWrongState = newCompetition().withCompetitionStatus(CompetitionStatus.READY_TO_OPEN).build(); when(sectionRepositoryMock.findFirstByCompetitionIdAndName(competitionInWrongState.getId(), APPLICATION_QUESTIONS.getName())).thenReturn(null); ServiceResult<Question> result = service.addDefaultAssessedQuestionToCompetition(competitionInWrongState); assertTrue(result.isFailure()); }
### Question: InviteUserPermissionRules extends BasePermissionRules { @PermissionRule(value = "SAVE_USER_INVITE", description = "Only an IFS Administrator can save a new user invite") public boolean ifsAdminCanSaveNewUserInvite(final UserResource invitedUser, UserResource user) { return user.hasRole(IFS_ADMINISTRATOR); } @PermissionRule(value = "SAVE_USER_INVITE", description = "Only an IFS Administrator can save a new user invite") boolean ifsAdminCanSaveNewUserInvite(final UserResource invitedUser, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view pending internal user invites") boolean internalUsersCanViewPendingInternalUserInvites(RoleInvitePageResource invite, UserResource user); }### Answer: @Test public void ifsAdminCanSaveNewUserInvite() { assertTrue(rules.ifsAdminCanSaveNewUserInvite(invitedUser, ifsAdmin)); assertFalse(rules.ifsAdminCanSaveNewUserInvite(invitedUser, nonIfsAdmin)); }
### Question: InviteUserPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ", description = "Internal users can view pending internal user invites") public boolean internalUsersCanViewPendingInternalUserInvites(RoleInvitePageResource invite, UserResource user) { return user.hasRole(IFS_ADMINISTRATOR); } @PermissionRule(value = "SAVE_USER_INVITE", description = "Only an IFS Administrator can save a new user invite") boolean ifsAdminCanSaveNewUserInvite(final UserResource invitedUser, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view pending internal user invites") boolean internalUsersCanViewPendingInternalUserInvites(RoleInvitePageResource invite, UserResource user); }### Answer: @Test public void internalUsersCanViewPendingInternalUserInvites() { RoleInvitePageResource invite = new RoleInvitePageResource(); assertTrue(rules.internalUsersCanViewPendingInternalUserInvites(invite, ifsAdmin)); assertFalse(rules.internalUsersCanViewPendingInternalUserInvites(invite, nonIfsAdmin)); }
### Question: ApplicationInviteLookupStrategy { @PermissionEntityLookupStrategy public ApplicationInviteResource getApplicationInviteResource(final Long id){ return applicationInviteMapper.mapToResource(applicationInviteRepository.findById(id).orElse(null)); } @PermissionEntityLookupStrategy ApplicationInviteResource getApplicationInviteResource(final Long id); }### Answer: @Test public void testFindById() { ApplicationInviteResource applicationInviteResource = newApplicationInviteResource().withId(inviteId).build(); ApplicationInvite applicationInvite = newApplicationInvite().withId(inviteId).build(); when(applicationInviteMapper.mapToResource(applicationInvite)).thenReturn(applicationInviteResource); when(applicationInviteRepository.findById(inviteId)).thenReturn(Optional.of(applicationInvite)); assertEquals(applicationInviteResource, lookup.getApplicationInviteResource(inviteId)); }
### Question: ApplicationKtaInviteLookupStrategy { @PermissionEntityLookupStrategy public ApplicationKtaInviteResource getApplicationInviteResource(final Long id){ return applicationKtaInviteMapper.mapToResource(applicationKtaInviteRepository.findById(id).orElse(null)); } @PermissionEntityLookupStrategy ApplicationKtaInviteResource getApplicationInviteResource(final Long id); @PermissionEntityLookupStrategy ApplicationKtaInviteResource getKtaInviteByHash(final String hash); }### Answer: @Test public void findById() { ApplicationKtaInviteResource applicationKtaInviteResource = newApplicationKtaInviteResource().withId(inviteId).build(); ApplicationKtaInvite applicationKtaInvite = newApplicationKtaInvite().withId(inviteId).build(); when(applicationKtaInviteMapper.mapToResource(applicationKtaInvite)).thenReturn(applicationKtaInviteResource); when(applicationKtaInviteRepository.findById(inviteId)).thenReturn(Optional.of(applicationKtaInvite)); assertEquals(applicationKtaInviteResource, lookup.getApplicationInviteResource(inviteId)); }
### Question: ApplicationKtaInviteLookupStrategy { @PermissionEntityLookupStrategy public ApplicationKtaInviteResource getKtaInviteByHash(final String hash){ return applicationKtaInviteMapper.mapToResource(applicationKtaInviteRepository.getByHash(hash)); } @PermissionEntityLookupStrategy ApplicationKtaInviteResource getApplicationInviteResource(final Long id); @PermissionEntityLookupStrategy ApplicationKtaInviteResource getKtaInviteByHash(final String hash); }### Answer: @Test public void findByHash() { ApplicationKtaInviteResource applicationKtaInviteResource = newApplicationKtaInviteResource().withId(inviteId).build(); ApplicationKtaInvite applicationKtaInvite = newApplicationKtaInvite().withId(inviteId).build(); when(applicationKtaInviteMapper.mapToResource(applicationKtaInvite)).thenReturn(applicationKtaInviteResource); when(applicationKtaInviteRepository.getByHash(hash)).thenReturn(applicationKtaInvite); assertEquals(applicationKtaInviteResource, lookup.getKtaInviteByHash(hash)); }
### Question: ApplicationKtaInviteController { @PostMapping("/resend-kta-invite") public RestResult<Void> resendKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource) { return applicationKtaInviteService.resendKtaInvite(inviteResource).toPostCreateResponse(); } @GetMapping("/get-kta-invite-by-application-id/{applicationId}") RestResult<ApplicationKtaInviteResource> getKtaInviteByApplication(@PathVariable long applicationId); @PostMapping("/save-kta-invite") RestResult<Void> saveKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @PostMapping("/resend-kta-invite") RestResult<Void> resendKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @DeleteMapping("/remove-kta-invite-by-application/{applicationId}") RestResult<Void> removeKtaInvite(@PathVariable("applicationId") long applicationId); @GetMapping("/hash/{hash}") RestResult<ApplicationKtaInviteResource> getKtaInviteByHash(@PathVariable String hash); @PostMapping("/hash/{hash}") RestResult<Void> acceptInvite(@PathVariable String hash); }### Answer: @Test public void resendKtaInvite() throws Exception { long applicationId = 1L; ApplicationKtaInviteResource inviteResource = newApplicationKtaInviteResource() .withApplication(applicationId) .withEmail("testemail") .build(); when(applicationKtaInviteService.resendKtaInvite(inviteResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/kta-invite/resend-kta-invite") .contentType(APPLICATION_JSON) .content(toJson(inviteResource))) .andExpect(status().isCreated()); }
### Question: ApplicationKtaInviteController { @PostMapping("/save-kta-invite") public RestResult<Void> saveKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource) { return applicationKtaInviteService.saveKtaInvite(inviteResource).toPostCreateResponse(); } @GetMapping("/get-kta-invite-by-application-id/{applicationId}") RestResult<ApplicationKtaInviteResource> getKtaInviteByApplication(@PathVariable long applicationId); @PostMapping("/save-kta-invite") RestResult<Void> saveKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @PostMapping("/resend-kta-invite") RestResult<Void> resendKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @DeleteMapping("/remove-kta-invite-by-application/{applicationId}") RestResult<Void> removeKtaInvite(@PathVariable("applicationId") long applicationId); @GetMapping("/hash/{hash}") RestResult<ApplicationKtaInviteResource> getKtaInviteByHash(@PathVariable String hash); @PostMapping("/hash/{hash}") RestResult<Void> acceptInvite(@PathVariable String hash); }### Answer: @Test public void saveKtaInvite() throws Exception { long applicationId = 1L; ApplicationKtaInviteResource inviteResource = newApplicationKtaInviteResource() .withApplication(applicationId) .withEmail("testemail") .build(); when(applicationKtaInviteService.saveKtaInvite(inviteResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/kta-invite/save-kta-invite") .contentType(APPLICATION_JSON) .content(toJson(inviteResource))) .andExpect(status().isCreated()); }
### Question: ApplicationKtaInviteController { @DeleteMapping("/remove-kta-invite-by-application/{applicationId}") public RestResult<Void> removeKtaInvite(@PathVariable("applicationId") long applicationId) { return applicationKtaInviteService.removeKtaInviteByApplication(applicationId).toDeleteResponse(); } @GetMapping("/get-kta-invite-by-application-id/{applicationId}") RestResult<ApplicationKtaInviteResource> getKtaInviteByApplication(@PathVariable long applicationId); @PostMapping("/save-kta-invite") RestResult<Void> saveKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @PostMapping("/resend-kta-invite") RestResult<Void> resendKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @DeleteMapping("/remove-kta-invite-by-application/{applicationId}") RestResult<Void> removeKtaInvite(@PathVariable("applicationId") long applicationId); @GetMapping("/hash/{hash}") RestResult<ApplicationKtaInviteResource> getKtaInviteByHash(@PathVariable String hash); @PostMapping("/hash/{hash}") RestResult<Void> acceptInvite(@PathVariable String hash); }### Answer: @Test public void removeKtaInvite() throws Exception { long applicationId = 456L; when(applicationKtaInviteService.removeKtaInviteByApplication(applicationId)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/kta-invite/remove-kta-invite-by-application/"+applicationId)) .andExpect(status().isNoContent()); }
### Question: ApplicationKtaInviteController { @GetMapping("/get-kta-invite-by-application-id/{applicationId}") public RestResult<ApplicationKtaInviteResource> getKtaInviteByApplication(@PathVariable long applicationId) { return applicationKtaInviteService.getKtaInviteByApplication(applicationId).toGetResponse(); } @GetMapping("/get-kta-invite-by-application-id/{applicationId}") RestResult<ApplicationKtaInviteResource> getKtaInviteByApplication(@PathVariable long applicationId); @PostMapping("/save-kta-invite") RestResult<Void> saveKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @PostMapping("/resend-kta-invite") RestResult<Void> resendKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @DeleteMapping("/remove-kta-invite-by-application/{applicationId}") RestResult<Void> removeKtaInvite(@PathVariable("applicationId") long applicationId); @GetMapping("/hash/{hash}") RestResult<ApplicationKtaInviteResource> getKtaInviteByHash(@PathVariable String hash); @PostMapping("/hash/{hash}") RestResult<Void> acceptInvite(@PathVariable String hash); }### Answer: @Test public void getKtaInviteByApplication() throws Exception { long applicationId = 1L; ApplicationKtaInviteResource inviteResource = newApplicationKtaInviteResource() .build(); when(applicationKtaInviteService.getKtaInviteByApplication(applicationId)).thenReturn(serviceSuccess(inviteResource)); mockMvc.perform(get("/kta-invite/get-kta-invite-by-application-id/{applicationId}", applicationId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json(toJson(inviteResource))); }
### Question: ApplicationKtaInviteController { @GetMapping("/hash/{hash}") public RestResult<ApplicationKtaInviteResource> getKtaInviteByHash(@PathVariable String hash) { return applicationKtaInviteService.getKtaInviteByHash(hash).toGetResponse(); } @GetMapping("/get-kta-invite-by-application-id/{applicationId}") RestResult<ApplicationKtaInviteResource> getKtaInviteByApplication(@PathVariable long applicationId); @PostMapping("/save-kta-invite") RestResult<Void> saveKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @PostMapping("/resend-kta-invite") RestResult<Void> resendKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @DeleteMapping("/remove-kta-invite-by-application/{applicationId}") RestResult<Void> removeKtaInvite(@PathVariable("applicationId") long applicationId); @GetMapping("/hash/{hash}") RestResult<ApplicationKtaInviteResource> getKtaInviteByHash(@PathVariable String hash); @PostMapping("/hash/{hash}") RestResult<Void> acceptInvite(@PathVariable String hash); }### Answer: @Test public void getKtaInviteByHash() throws Exception { String hash = "hash"; ApplicationKtaInviteResource inviteResource = newApplicationKtaInviteResource() .build(); when(applicationKtaInviteService.getKtaInviteByHash(hash)).thenReturn(serviceSuccess(inviteResource)); mockMvc.perform(get("/kta-invite/hash/{hash}", hash) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json(toJson(inviteResource))); }
### Question: ApplicationKtaInviteController { @PostMapping("/hash/{hash}") public RestResult<Void> acceptInvite(@PathVariable String hash) { return applicationKtaInviteService.acceptInvite(hash).toGetResponse(); } @GetMapping("/get-kta-invite-by-application-id/{applicationId}") RestResult<ApplicationKtaInviteResource> getKtaInviteByApplication(@PathVariable long applicationId); @PostMapping("/save-kta-invite") RestResult<Void> saveKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @PostMapping("/resend-kta-invite") RestResult<Void> resendKtaInvite(@RequestBody ApplicationKtaInviteResource inviteResource); @DeleteMapping("/remove-kta-invite-by-application/{applicationId}") RestResult<Void> removeKtaInvite(@PathVariable("applicationId") long applicationId); @GetMapping("/hash/{hash}") RestResult<ApplicationKtaInviteResource> getKtaInviteByHash(@PathVariable String hash); @PostMapping("/hash/{hash}") RestResult<Void> acceptInvite(@PathVariable String hash); }### Answer: @Test public void acceptInvite() throws Exception { String hash = "hash"; when(applicationKtaInviteService.acceptInvite(hash)).thenReturn(serviceSuccess()); mockMvc.perform(post("/kta-invite/hash/{hash}", hash) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()); verify(applicationKtaInviteService).acceptInvite(hash); }
### Question: InviteUserController { @PostMapping("/save-invite") public RestResult<Void> saveUserInvite(@RequestBody InviteUserResource inviteUserResource) { return inviteUserService.saveUserInvite(inviteUserResource.getInvitedUser(), inviteUserResource.getRole()).toPostResponse(); } @PostMapping("/save-invite") RestResult<Void> saveUserInvite(@RequestBody InviteUserResource inviteUserResource); @GetMapping("/get-invite/{inviteHash}") RestResult<RoleInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String inviteHash); @GetMapping("/internal/pending") RestResult<RoleInvitePageResource> findPendingInternalUserInvites(@RequestParam(required = false) String filter, @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex, @RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PutMapping("/internal/pending/{inviteId}/resend") RestResult<Void> resendPendingInternalUserInvite(@PathVariable("inviteId") long inviteId); @GetMapping("/find-external-invites") RestResult<List<ExternalInviteResource>> findExternalInvites(@RequestParam(value = "searchString") final String searchString, @RequestParam(value = "searchCategory") final SearchCategory searchCategory); }### Answer: @Test public void saveUserInvite() throws Exception { when(inviteUserServiceMock.saveUserInvite(inviteUserResource.getInvitedUser(), inviteUserResource.getRole())).thenReturn(serviceSuccess()); mockMvc.perform(post("/invite-user/save-invite") .contentType(APPLICATION_JSON) .content(toJson(inviteUserResource))) .andExpect(status().isOk()); verify(inviteUserServiceMock).saveUserInvite(inviteUserResource.getInvitedUser(), inviteUserResource.getRole()); }
### Question: InviteUserController { @GetMapping("/get-invite/{inviteHash}") public RestResult<RoleInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash){ return inviteUserService.getInvite(inviteHash).toGetResponse(); } @PostMapping("/save-invite") RestResult<Void> saveUserInvite(@RequestBody InviteUserResource inviteUserResource); @GetMapping("/get-invite/{inviteHash}") RestResult<RoleInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String inviteHash); @GetMapping("/internal/pending") RestResult<RoleInvitePageResource> findPendingInternalUserInvites(@RequestParam(required = false) String filter, @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex, @RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PutMapping("/internal/pending/{inviteId}/resend") RestResult<Void> resendPendingInternalUserInvite(@PathVariable("inviteId") long inviteId); @GetMapping("/find-external-invites") RestResult<List<ExternalInviteResource>> findExternalInvites(@RequestParam(value = "searchString") final String searchString, @RequestParam(value = "searchCategory") final SearchCategory searchCategory); }### Answer: @Test public void getInvite() throws Exception { when(inviteUserServiceMock.getInvite("SomeHashString")).thenReturn(serviceSuccess(new RoleInviteResource())); mockMvc.perform(get("/invite-user/get-invite/SomeHashString")).andExpect(status().isOk()); verify(inviteUserServiceMock).getInvite("SomeHashString"); }
### Question: InviteUserController { @GetMapping("/check-existing-user/{inviteHash}") public RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String inviteHash) { return inviteUserService.checkExistingUser(inviteHash).toGetResponse(); } @PostMapping("/save-invite") RestResult<Void> saveUserInvite(@RequestBody InviteUserResource inviteUserResource); @GetMapping("/get-invite/{inviteHash}") RestResult<RoleInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String inviteHash); @GetMapping("/internal/pending") RestResult<RoleInvitePageResource> findPendingInternalUserInvites(@RequestParam(required = false) String filter, @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex, @RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PutMapping("/internal/pending/{inviteId}/resend") RestResult<Void> resendPendingInternalUserInvite(@PathVariable("inviteId") long inviteId); @GetMapping("/find-external-invites") RestResult<List<ExternalInviteResource>> findExternalInvites(@RequestParam(value = "searchString") final String searchString, @RequestParam(value = "searchCategory") final SearchCategory searchCategory); }### Answer: @Test public void checkExistingUser() throws Exception { when(inviteUserServiceMock.checkExistingUser("SomeHashString")).thenReturn(serviceSuccess(true)); mockMvc.perform(get("/invite-user/check-existing-user/SomeHashString")).andExpect(status().isOk()); verify(inviteUserServiceMock).checkExistingUser("SomeHashString"); }
### Question: InviteOrganisationController { @GetMapping("/{id}") public RestResult<InviteOrganisationResource> getById(@PathVariable("id") long id) { return service.getById(id).toGetResponse(); } @GetMapping("/{id}") RestResult<InviteOrganisationResource> getById(@PathVariable("id") long id); @GetMapping("/organisation/{organisationId}/application/{applicationId}") RestResult<InviteOrganisationResource> getByOrganisationIdWithInvitesForApplication(@PathVariable("organisationId") long organisationId, @PathVariable("applicationId") long applicationId); @PutMapping("/save") RestResult<Void> put(@RequestBody InviteOrganisationResource inviteOrganisationResource); }### Answer: @Test public void getById() throws Exception { InviteOrganisationResource inviteOrganisationResource = newInviteOrganisationResource().build(); when(inviteOrganisationServiceMock.getById(inviteOrganisationResource.getId())) .thenReturn(serviceSuccess(inviteOrganisationResource)); mockMvc.perform(get("/inviteorganisation/{id}", inviteOrganisationResource.getId())) .andExpect(status().isOk()) .andExpect(content().json(toJson(inviteOrganisationResource))); verify(inviteOrganisationServiceMock, only()).getById(inviteOrganisationResource.getId()); }
### Question: InviteOrganisationController { @GetMapping("/organisation/{organisationId}/application/{applicationId}") public RestResult<InviteOrganisationResource> getByOrganisationIdWithInvitesForApplication(@PathVariable("organisationId") long organisationId, @PathVariable("applicationId") long applicationId) { return service.getByOrganisationIdWithInvitesForApplication(organisationId, applicationId).toGetResponse(); } @GetMapping("/{id}") RestResult<InviteOrganisationResource> getById(@PathVariable("id") long id); @GetMapping("/organisation/{organisationId}/application/{applicationId}") RestResult<InviteOrganisationResource> getByOrganisationIdWithInvitesForApplication(@PathVariable("organisationId") long organisationId, @PathVariable("applicationId") long applicationId); @PutMapping("/save") RestResult<Void> put(@RequestBody InviteOrganisationResource inviteOrganisationResource); }### Answer: @Test public void getByOrganisationIdWithInvitesForApplication() throws Exception { long organisationId = 1L; long applicationId = 2L; InviteOrganisationResource inviteOrganisationResource = newInviteOrganisationResource().build(); when(inviteOrganisationServiceMock.getByOrganisationIdWithInvitesForApplication(inviteOrganisationResource.getId(), applicationId)) .thenReturn(serviceSuccess(inviteOrganisationResource)); mockMvc.perform(get("/inviteorganisation/organisation/{organisationId}/application/{applicationId}", organisationId, applicationId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(inviteOrganisationResource))); verify(inviteOrganisationServiceMock, only()).getByOrganisationIdWithInvitesForApplication(organisationId, applicationId); }
### Question: RejectionReasonController { @GetMapping("/find-all-active") public RestResult<List<RejectionReasonResource>> findAllActive() { return rejectionReasonService.findAllActive().toGetResponse(); } @GetMapping("/find-all-active") RestResult<List<RejectionReasonResource>> findAllActive(); }### Answer: @Test public void findAllActive() throws Exception { List<RejectionReasonResource> expected = newRejectionReasonResource().build(2); when(rejectionReasonServiceMock.findAllActive()).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/rejection-reason/find-all-active")) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(2))) .andExpect(content().string(objectMapper.writeValueAsString(expected))); verify(rejectionReasonServiceMock, only()).findAllActive(); }
### Question: ApplicationKtaInviteServiceImpl extends InviteService<ApplicationKtaInvite> implements ApplicationKtaInviteService { @Override public ServiceResult<ApplicationKtaInviteResource> getKtaInviteByHash(String hash) { return getByHash(hash) .andOnSuccessReturn(this::mapInviteToKtaInviteResource); } @Override ServiceResult<ApplicationKtaInviteResource> getKtaInviteByApplication(long applicationId); @Override ServiceResult<Void> resendKtaInvite(ApplicationKtaInviteResource inviteResource); @Override @Transactional ServiceResult<Void> removeKtaInviteByApplication(long applicationId); @Override @Transactional ServiceResult<Void> saveKtaInvite(ApplicationKtaInviteResource inviteResource); @Override ServiceResult<ApplicationKtaInviteResource> getKtaInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(String hash); }### Answer: @Test public void getKtaInviteByHash() { String hash = "hash"; long leadOrganisationId = 31L; Organisation leadOrganisation = newOrganisation().withName("Empire Ltd").withId(leadOrganisationId).build(); ApplicationKtaInviteResource inviteResource = newApplicationKtaInviteResource().build(); ApplicationKtaInvite invite = new ApplicationKtaInvite(); when(applicationKtaInviteRepository.getByHash(hash)).thenReturn(invite); when(applicationKtaInviteMapper.mapToResource(invite)).thenReturn(inviteResource); when(organisationRepository.findById(inviteResource.getLeadOrganisationId())).thenReturn(Optional.of(leadOrganisation)); ServiceResult<ApplicationKtaInviteResource> result = inviteKtaService.getKtaInviteByHash(hash); assertTrue(result.isSuccess()); assertEquals(result.getSuccess(), inviteResource); }
### Question: ApplicationKtaInviteServiceImpl extends InviteService<ApplicationKtaInvite> implements ApplicationKtaInviteService { @Override @Transactional public ServiceResult<Void> acceptInvite(String hash) { return getByHash(hash) .andOnSuccess(invite -> { applicationKtaInviteRepository.save(invite.open()); ProcessRole ktaProcessRole = new ProcessRole(invite.getUser(), invite.getTarget().getId(), Role.KNOWLEDGE_TRANSFER_ADVISER); processRoleRepository.save(ktaProcessRole); return serviceSuccess(); }); } @Override ServiceResult<ApplicationKtaInviteResource> getKtaInviteByApplication(long applicationId); @Override ServiceResult<Void> resendKtaInvite(ApplicationKtaInviteResource inviteResource); @Override @Transactional ServiceResult<Void> removeKtaInviteByApplication(long applicationId); @Override @Transactional ServiceResult<Void> saveKtaInvite(ApplicationKtaInviteResource inviteResource); @Override ServiceResult<ApplicationKtaInviteResource> getKtaInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(String hash); }### Answer: @Test public void acceptInvite() { String hash = "hash"; ApplicationKtaInvite invite = mock(ApplicationKtaInvite.class); when(applicationKtaInviteRepository.getByHash(hash)).thenReturn(invite); when(invite.getTarget()).thenReturn(newApplication().build()); when(invite.getUser()).thenReturn(newUser().build()); ServiceResult<Void> result = inviteKtaService.acceptInvite(hash); assertTrue(result.isSuccess()); verify(processRoleRepository).save(any(ProcessRole.class)); verify(applicationKtaInviteRepository).save(invite.open()); }
### Question: InviteOrganisationServiceImpl extends BaseTransactionalService implements InviteOrganisationService { @Override public ServiceResult<InviteOrganisationResource> getById(long id) { return find(inviteOrganisationRepository.findById(id), notFoundError(InviteOrganisation.class, id)) .andOnSuccessReturn(mapper::mapToResource); } @Override ServiceResult<InviteOrganisationResource> getById(long id); @Override ServiceResult<InviteOrganisationResource> getByOrganisationIdWithInvitesForApplication(long organisationId, long applicationId); @Override @Transactional ServiceResult<InviteOrganisationResource> save(InviteOrganisationResource inviteOrganisationResource); }### Answer: @Test public void getById() throws Exception { InviteOrganisation inviteOrganisation = newInviteOrganisation().build(); InviteOrganisationResource inviteOrganisationResource = newInviteOrganisationResource().build(); when(inviteOrganisationRepositoryMock.findById(inviteOrganisation.getId())).thenReturn(Optional.of(inviteOrganisation)); when(inviteOrganisationMapperMock.mapToResource(inviteOrganisation)).thenReturn(inviteOrganisationResource); ServiceResult<InviteOrganisationResource> result = service.getById(inviteOrganisation.getId()); assertEquals(inviteOrganisationResource, result.getSuccess()); InOrder inOrder = inOrder(inviteOrganisationRepositoryMock, inviteOrganisationMapperMock); inOrder.verify(inviteOrganisationRepositoryMock).findById(inviteOrganisation.getId()); inOrder.verify(inviteOrganisationMapperMock).mapToResource(inviteOrganisation); inOrder.verifyNoMoreInteractions(); }
### Question: InviteOrganisationServiceImpl extends BaseTransactionalService implements InviteOrganisationService { @Override public ServiceResult<InviteOrganisationResource> getByOrganisationIdWithInvitesForApplication(long organisationId, long applicationId) { return find(inviteOrganisationRepository.findOneByOrganisationIdAndInvitesApplicationId(organisationId, applicationId), notFoundError(InviteOrganisation.class, asList(organisationId, applicationId))).andOnSuccessReturn(mapper::mapToResource); } @Override ServiceResult<InviteOrganisationResource> getById(long id); @Override ServiceResult<InviteOrganisationResource> getByOrganisationIdWithInvitesForApplication(long organisationId, long applicationId); @Override @Transactional ServiceResult<InviteOrganisationResource> save(InviteOrganisationResource inviteOrganisationResource); }### Answer: @Test public void getByOrganisationIdWithInvitesForApplication() throws Exception { long organisationId = 1L; long applicationId = 2L; InviteOrganisation inviteOrganisation = newInviteOrganisation().build(); InviteOrganisationResource inviteOrganisationResource = newInviteOrganisationResource().build(); when(inviteOrganisationRepositoryMock.findOneByOrganisationIdAndInvitesApplicationId(organisationId, applicationId)).thenReturn(inviteOrganisation); when(inviteOrganisationMapperMock.mapToResource(inviteOrganisation)).thenReturn(inviteOrganisationResource); ServiceResult<InviteOrganisationResource> result = service.getByOrganisationIdWithInvitesForApplication(organisationId, applicationId); assertEquals(inviteOrganisationResource, result.getSuccess()); InOrder inOrder = inOrder(inviteOrganisationRepositoryMock, inviteOrganisationMapperMock); inOrder.verify(inviteOrganisationRepositoryMock).findOneByOrganisationIdAndInvitesApplicationId(organisationId, applicationId); inOrder.verify(inviteOrganisationMapperMock).mapToResource(inviteOrganisation); inOrder.verifyNoMoreInteractions(); }
### Question: RejectionReasonServiceImpl implements RejectionReasonService { @Override public ServiceResult<List<RejectionReasonResource>> findAllActive() { return serviceSuccess(simpleMap(rejectionReasonRepository.findByActiveTrueOrderByPriorityAsc(), rejectionReasonMapper::mapToResource)); } @Override ServiceResult<List<RejectionReasonResource>> findAllActive(); @Override ServiceResult<RejectionReasonResource> findById(Long id); }### Answer: @Test public void findAllActive() throws Exception { List<RejectionReasonResource> rejectionReasonResources = newRejectionReasonResource().build(2); List<RejectionReason> rejectionReasons = newRejectionReason().build(2); when(rejectionReasonRepositoryMock.findByActiveTrueOrderByPriorityAsc()).thenReturn(rejectionReasons); when(rejectionReasonMapperMock.mapToResource(same(rejectionReasons.get(0)))).thenReturn(rejectionReasonResources.get(0)); when(rejectionReasonMapperMock.mapToResource(same(rejectionReasons.get(1)))).thenReturn(rejectionReasonResources.get(1)); List<RejectionReasonResource> found = rejectionReasonService.findAllActive().getSuccess(); assertEquals(rejectionReasonResources, found); InOrder inOrder = inOrder(rejectionReasonRepositoryMock, rejectionReasonMapperMock); inOrder.verify(rejectionReasonRepositoryMock, calls(1)).findByActiveTrueOrderByPriorityAsc(); inOrder.verify(rejectionReasonMapperMock, calls(2)).mapToResource(isA(RejectionReason.class)); inOrder.verifyNoMoreInteractions(); }
### Question: RejectionReasonServiceImpl implements RejectionReasonService { @Override public ServiceResult<RejectionReasonResource> findById(Long id) { return find(rejectionReasonRepository.findById(id), notFoundError(RejectionReason.class, id)).andOnSuccessReturn(rejectionReasonMapper::mapToResource); } @Override ServiceResult<List<RejectionReasonResource>> findAllActive(); @Override ServiceResult<RejectionReasonResource> findById(Long id); }### Answer: @Test public void findById() throws Exception { Long rejectionReasonId = 1L; RejectionReasonResource rejectionReasonResource = newRejectionReasonResource().build(); RejectionReason rejectionReason = newRejectionReason().build(); when(rejectionReasonRepositoryMock.findById(rejectionReasonId)).thenReturn(Optional.of(rejectionReason)); when(rejectionReasonMapperMock.mapToResource(same(rejectionReason))).thenReturn(rejectionReasonResource); RejectionReasonResource found = rejectionReasonService.findById(rejectionReasonId).getSuccess(); assertEquals(rejectionReasonResource, found); InOrder inOrder = inOrder(rejectionReasonRepositoryMock, rejectionReasonMapperMock); inOrder.verify(rejectionReasonRepositoryMock, calls(1)).findById(rejectionReasonId); inOrder.verify(rejectionReasonMapperMock, calls(1)).mapToResource(rejectionReason); inOrder.verifyNoMoreInteractions(); }
### Question: InviteUserServiceImpl extends BaseTransactionalService implements InviteUserService { @Override public ServiceResult<RoleInviteResource> getInvite(String inviteHash) { RoleInvite roleInvite = roleInviteRepository.getByHash(inviteHash); return serviceSuccess(roleInviteMapper.mapToResource(roleInvite)); } @Override @Transactional ServiceResult<Void> saveUserInvite(UserResource invitedUser, Role role); @Override ServiceResult<RoleInviteResource> getInvite(String inviteHash); @Override ServiceResult<Boolean> checkExistingUser(String inviteHash); @Override ServiceResult<RoleInvitePageResource> findPendingInternalUserInvites(String filter, Pageable pageable); @Override ServiceResult<List<ExternalInviteResource>> findExternalInvites(String searchString, SearchCategory searchCategory); @Override ServiceResult<Void> resendInvite(long inviteId); static final String INTERNAL_USER_WEB_CONTEXT; static final String EXTERNAL_USER_WEB_CONTEXT; }### Answer: @Test public void testGetInvite(){ RoleInvite roleInvite = newRoleInvite().build(); when(roleInviteRepositoryMock.getByHash("SomeInviteHash")).thenReturn(roleInvite); when(roleInviteMapperMock.mapToResource(roleInvite)).thenReturn(newRoleInviteResource().build()); ServiceResult<RoleInviteResource> result = service.getInvite("SomeInviteHash"); assertTrue(result.isSuccess()); }
### Question: InviteUserServiceImpl extends BaseTransactionalService implements InviteUserService { @Override public ServiceResult<Boolean> checkExistingUser(String inviteHash) { return getByHash(inviteHash) .andOnSuccessReturn(i -> userRepository.findByEmail(i.getEmail())) .andOnSuccess(u -> serviceSuccess(u.isPresent())); } @Override @Transactional ServiceResult<Void> saveUserInvite(UserResource invitedUser, Role role); @Override ServiceResult<RoleInviteResource> getInvite(String inviteHash); @Override ServiceResult<Boolean> checkExistingUser(String inviteHash); @Override ServiceResult<RoleInvitePageResource> findPendingInternalUserInvites(String filter, Pageable pageable); @Override ServiceResult<List<ExternalInviteResource>> findExternalInvites(String searchString, SearchCategory searchCategory); @Override ServiceResult<Void> resendInvite(long inviteId); static final String INTERNAL_USER_WEB_CONTEXT; static final String EXTERNAL_USER_WEB_CONTEXT; }### Answer: @Test public void testCheckExistingUser(){ RoleInvite roleInvite = newRoleInvite().build(); when(roleInviteRepositoryMock.getByHash("SomeInviteHash")).thenReturn(roleInvite); when(userRepositoryMock.findByEmail(roleInvite.getEmail())).thenReturn(Optional.of(newUser().build())); ServiceResult<Boolean> result = service.checkExistingUser("SomeInviteHash"); assertTrue(result.isSuccess()); assertTrue(result.getSuccess()); }
### Question: ApplicationInviteServiceImpl extends InviteService<ApplicationInvite> implements ApplicationInviteService { @Override public ServiceResult<ApplicationInvite> findOneByHash(String hash) { return getByHash(hash); } @Override ServiceResult<ApplicationInvite> findOneByHash(String hash); @Override @Transactional ServiceResult<Void> createApplicationInvites(InviteOrganisationResource inviteOrganisationResource, Optional<Long> applicationId); @Override ServiceResult<InviteOrganisationResource> getInviteOrganisationByHash(String hash); @Override ServiceResult<List<InviteOrganisationResource>> getInvitesByApplication(Long applicationId); @Override @Transactional ServiceResult<Void> saveInvites(List<ApplicationInviteResource> inviteResources); @Override @Transactional ServiceResult<Void> resendInvite(ApplicationInviteResource inviteResource); @Override ServiceResult<ApplicationInviteResource> getInviteByHash(String hash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<UserResource> getUserByInviteHash(String hash); @Override @Transactional ServiceResult<Void> removeApplicationInvite(long applicationInviteId); }### Answer: @Test public void findOneByHash() { String hash = "123abc"; ApplicationInvite applicationInvite = newApplicationInvite().build(); when(applicationInviteRepository.getByHash(hash)).thenReturn(applicationInvite); ServiceResult<ApplicationInvite> result = inviteService.findOneByHash(hash); assertThat(result.getSuccess()).isEqualTo(applicationInvite); }
### Question: ProjectUserInvite extends ProjectInvite<ProjectUserInvite> { public Organisation getOrganisation() { return organisation; } ProjectUserInvite(); ProjectUserInvite(final String name, final String email, final String hash, final Organisation organisation, final Project project, final InviteStatus status); Organisation getOrganisation(); void setOrganisation(final Organisation organisation); }### Answer: @Test public void constructedProjectInviteShouldReturnCorrectAttributes() throws Exception { assertEquals(name, constructedInvite.getName()); assertEquals(email, constructedInvite.getEmail()); assertEquals(project, constructedInvite.getTarget()); assertEquals(hash, constructedInvite.getHash()); assertEquals(organisation, constructedInvite.getOrganisation()); assertEquals(status, constructedInvite.getStatus()); } @Test public void gettingProjectInviteAnyAttributeAfterSettingShouldReturnCorrectValue() throws Exception { assertEquals(inviteId, setInvite.getId()); assertEquals(name, setInvite.getName()); assertEquals(email, setInvite.getEmail()); assertEquals(project, setInvite.getTarget()); assertEquals(hash, setInvite.getHash()); assertEquals(organisation, setInvite.getOrganisation()); }
### Question: ActivityLogServiceImpl implements ActivityLogService { @Override public void recordActivityByApplicationId(long applicationId, ActivityType activityType) { applicationRepository.findById(applicationId) .ifPresent(application -> { ActivityLog log = new ActivityLog(application, activityType); activityLogRepository.save(log); }); } @Override void recordActivityByApplicationId(long applicationId, ActivityType activityType); @Override void recordActivityByProjectId(long projectId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationIdAndAuthorId(long projectId, long organisationId, long authorId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationId(long projectId, long organisationId, ActivityType activityType); @Override void recordDocumentActivityByProjectId(long projectId, ActivityType activityType, long documentConfigId); @Override void recordQueryActivityByProjectFinanceId(long projectFinanceId, ActivityType activityType, long threadId); @Transactional(readOnly = true) ServiceResult<List<ActivityLogResource>> findByApplicationId(long applicationId); }### Answer: @Test public void recordActivityByApplicationId() { Application application = newApplication().build(); when(applicationRepository.findById(application.getId())).thenReturn(Optional.of(application)); activityLogService.recordActivityByApplicationId(application.getId(), TEST_ACTIVITY_TYPE); verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE)); }
### Question: ActivityLogServiceImpl implements ActivityLogService { @Override public void recordActivityByProjectId(long projectId, ActivityType activityType) { projectRepository.findById(projectId) .ifPresent(project -> { ActivityLog log = new ActivityLog(project.getApplication(), activityType); activityLogRepository.save(log); }); } @Override void recordActivityByApplicationId(long applicationId, ActivityType activityType); @Override void recordActivityByProjectId(long projectId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationIdAndAuthorId(long projectId, long organisationId, long authorId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationId(long projectId, long organisationId, ActivityType activityType); @Override void recordDocumentActivityByProjectId(long projectId, ActivityType activityType, long documentConfigId); @Override void recordQueryActivityByProjectFinanceId(long projectFinanceId, ActivityType activityType, long threadId); @Transactional(readOnly = true) ServiceResult<List<ActivityLogResource>> findByApplicationId(long applicationId); }### Answer: @Test public void recordActivityByProjectId() { Application application = newApplication().build(); Project project = newProject().withApplication(application).build(); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project)); activityLogService.recordActivityByProjectId(project.getId(), TEST_ACTIVITY_TYPE); verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE)); }
### Question: ActivityLogServiceImpl implements ActivityLogService { @Override public void recordActivityByProjectIdAndOrganisationId(long projectId, long organisationId, ActivityType activityType) { projectRepository.findById(projectId) .ifPresent(project -> { organisationRepository.findById(organisationId).ifPresent(organisation -> { ActivityLog log = new ActivityLog(project.getApplication(), activityType, organisation); activityLogRepository.save(log); }); }); } @Override void recordActivityByApplicationId(long applicationId, ActivityType activityType); @Override void recordActivityByProjectId(long projectId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationIdAndAuthorId(long projectId, long organisationId, long authorId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationId(long projectId, long organisationId, ActivityType activityType); @Override void recordDocumentActivityByProjectId(long projectId, ActivityType activityType, long documentConfigId); @Override void recordQueryActivityByProjectFinanceId(long projectFinanceId, ActivityType activityType, long threadId); @Transactional(readOnly = true) ServiceResult<List<ActivityLogResource>> findByApplicationId(long applicationId); }### Answer: @Test public void recordActivityByProjectIdAndOrganisationId() { Application application = newApplication().build(); Project project = newProject().withApplication(application).build(); Organisation organisation = newOrganisation().build(); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); activityLogService.recordActivityByProjectIdAndOrganisationId(project.getId(), organisation.getId(), TEST_ACTIVITY_TYPE); verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE, organisation)); }
### Question: ActivityLogServiceImpl implements ActivityLogService { @Override public void recordDocumentActivityByProjectId(long projectId, ActivityType activityType, long documentConfigId) { projectRepository.findById(projectId) .ifPresent(project -> { competitionDocumentConfigRepository.findById(documentConfigId).ifPresent(document -> { ActivityLog log = new ActivityLog(project.getApplication(), activityType, document); activityLogRepository.save(log); }); }); } @Override void recordActivityByApplicationId(long applicationId, ActivityType activityType); @Override void recordActivityByProjectId(long projectId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationIdAndAuthorId(long projectId, long organisationId, long authorId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationId(long projectId, long organisationId, ActivityType activityType); @Override void recordDocumentActivityByProjectId(long projectId, ActivityType activityType, long documentConfigId); @Override void recordQueryActivityByProjectFinanceId(long projectFinanceId, ActivityType activityType, long threadId); @Transactional(readOnly = true) ServiceResult<List<ActivityLogResource>> findByApplicationId(long applicationId); }### Answer: @Test public void recordDocumentActivityByProjectId() { Application application = newApplication().build(); Project project = newProject().withApplication(application).build(); CompetitionDocument documentConfig = newCompetitionDocument().build(); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project)); when(competitionDocumentConfigRepository.findById(documentConfig.getId())).thenReturn(Optional.of(documentConfig)); activityLogService.recordDocumentActivityByProjectId(project.getId(), TEST_ACTIVITY_TYPE, documentConfig.getId()); verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE, documentConfig)); }
### Question: ActivityLogServiceImpl implements ActivityLogService { @Override public void recordQueryActivityByProjectFinanceId(long projectFinanceId, ActivityType activityType, long threadId) { projectFinanceRepository.findById(projectFinanceId) .ifPresent(projectFinance -> { queryRepository.findById(threadId).ifPresent(query -> { ActivityLog log = new ActivityLog(projectFinance.getProject().getApplication(), activityType, query, projectFinance.getOrganisation()); activityLogRepository.save(log); }); }); } @Override void recordActivityByApplicationId(long applicationId, ActivityType activityType); @Override void recordActivityByProjectId(long projectId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationIdAndAuthorId(long projectId, long organisationId, long authorId, ActivityType activityType); @Override void recordActivityByProjectIdAndOrganisationId(long projectId, long organisationId, ActivityType activityType); @Override void recordDocumentActivityByProjectId(long projectId, ActivityType activityType, long documentConfigId); @Override void recordQueryActivityByProjectFinanceId(long projectFinanceId, ActivityType activityType, long threadId); @Transactional(readOnly = true) ServiceResult<List<ActivityLogResource>> findByApplicationId(long applicationId); }### Answer: @Test public void recordQueryActivityByProjectFinanceId() { Application application = newApplication().build(); Project project = newProject().withApplication(application).build(); Organisation organisation = newOrganisation().build(); ProjectFinance projectFinance = newProjectFinance() .withProject(project) .withOrganisation(organisation) .build(); Query query = new Query(1L, null, null, null, null, null, null); when(projectFinanceRepository.findById(projectFinance.getId())).thenReturn(Optional.of(projectFinance)); when(queryRepository.findById(query.id())).thenReturn(Optional.of(query)); activityLogService.recordQueryActivityByProjectFinanceId(projectFinance.getId(),TEST_ACTIVITY_TYPE, query.id()); verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE, query, organisation)); }
### Question: ActivityLog { public User getAuthor() { return ofNullable(author).orElse(getCreatedBy()); } ActivityLog(); ActivityLog(Application application, ActivityType type, CompetitionDocument competitionDocument); ActivityLog(Application application, ActivityType type, Query query, Organisation organisation); ActivityLog(Application application, ActivityType type); ActivityLog(Application application, ActivityType type, Organisation organisation); ActivityLog(Application application, ActivityType type, Organisation organisation, User author); Long getId(); Application getApplication(); Optional<Organisation> getOrganisation(); ActivityType getType(); User getCreatedBy(); User getAuthor(); ZonedDateTime getCreatedOn(); Optional<CompetitionDocument> getCompetitionDocument(); Optional<Query> getQuery(); @Override boolean equals(Object o); @Override int hashCode(); boolean isOrganisationRemoved(); }### Answer: @Test public void testAuthorIsCreatedByWhenNotExpicitlySpecified(){ User createdBy = UserBuilder.newUser().build(); ActivityLog activityLog = newActivityLog().withCreatedBy(createdBy).build(); Assert.assertEquals(createdBy, activityLog.getAuthor()); }
### Question: EuGrantTransferServiceImpl implements EuGrantTransferService { @Override public ServiceResult<FileEntryResource> findGrantAgreement(long applicationId) { return findGrantTransferByApplicationId(applicationId).andOnSuccess(grantTransfer -> ofNullable(grantTransfer.getGrantAgreement()) .map(FileEntry::getId) .map(fileEntryService::findOne) .orElse(serviceFailure(notFoundError(FileEntryResource.class, applicationId)))); } @Override @Transactional ServiceResult<Void> uploadGrantAgreement(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteGrantAgreement(long applicationId); @Override ServiceResult<FileAndContents> downloadGrantAgreement(long applicationId); @Override ServiceResult<FileEntryResource> findGrantAgreement(long applicationId); @Override ServiceResult<EuGrantTransferResource> getGrantTransferByApplicationId(long applicationId); @Override @Transactional ServiceResult<Void> updateGrantTransferByApplicationId(EuGrantTransferResource euGrantTransferResource, long applicationId); }### Answer: @Test public void findGrantAgreement() { long applicationId = 1L; FileEntry fileEntry = newFileEntry().build(); EuGrantTransfer grantTransfer = newEuGrantTransfer() .withGrantAgreement(fileEntry) .build(); FileEntryResource fileEntryResource = newFileEntryResource().build(); when(euGrantTransferRepository.findByApplicationId(applicationId)).thenReturn(grantTransfer); when(fileEntryServiceMock.findOne(fileEntry.getId())).thenReturn(serviceSuccess(fileEntryResource)); FileEntryResource response = service.findGrantAgreement(applicationId).getSuccess(); assertEquals(fileEntryResource, response); }
### Question: EuGrantTransferServiceImpl implements EuGrantTransferService { @Override @Transactional public ServiceResult<Void> deleteGrantAgreement(long applicationId) { return findGrantTransferByApplicationId(applicationId).andOnSuccess(grantTransfer -> { long fileId = grantTransfer.getGrantAgreement().getId(); return fileService.deleteFileIgnoreNotFound(fileId).andOnSuccessReturnVoid(() -> grantTransfer.setGrantAgreement(null) ); }); } @Override @Transactional ServiceResult<Void> uploadGrantAgreement(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteGrantAgreement(long applicationId); @Override ServiceResult<FileAndContents> downloadGrantAgreement(long applicationId); @Override ServiceResult<FileEntryResource> findGrantAgreement(long applicationId); @Override ServiceResult<EuGrantTransferResource> getGrantTransferByApplicationId(long applicationId); @Override @Transactional ServiceResult<Void> updateGrantTransferByApplicationId(EuGrantTransferResource euGrantTransferResource, long applicationId); }### Answer: @Test public void deleteGrantAgreement() { final long applicationId = 1L; final long fileId = 101L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); EuGrantTransfer grantTransfer = newEuGrantTransfer() .withGrantAgreement(fileEntry) .build(); when(euGrantTransferRepository.findByApplicationId(applicationId)).thenReturn(grantTransfer); when(fileServiceMock.deleteFileIgnoreNotFound(fileId)).thenReturn(ServiceResult.serviceSuccess(fileEntry)); ServiceResult<Void> response = service.deleteGrantAgreement(applicationId); assertTrue(response.isSuccess()); assertNull(grantTransfer.getGrantAgreement()); verify(fileServiceMock).deleteFileIgnoreNotFound(fileId); }
### Question: EuGrantTransferServiceImpl implements EuGrantTransferService { @Override public ServiceResult<EuGrantTransferResource> getGrantTransferByApplicationId(long applicationId) { return findGrantTransferByApplicationId(applicationId).andOnSuccessReturn(mapper::mapToResource); } @Override @Transactional ServiceResult<Void> uploadGrantAgreement(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteGrantAgreement(long applicationId); @Override ServiceResult<FileAndContents> downloadGrantAgreement(long applicationId); @Override ServiceResult<FileEntryResource> findGrantAgreement(long applicationId); @Override ServiceResult<EuGrantTransferResource> getGrantTransferByApplicationId(long applicationId); @Override @Transactional ServiceResult<Void> updateGrantTransferByApplicationId(EuGrantTransferResource euGrantTransferResource, long applicationId); }### Answer: @Test public void getGrantTransferByApplicationId() { long applicationId = 1L; EuGrantTransfer grantTransfer = newEuGrantTransfer() .build(); EuGrantTransferResource grantTransferResource = newEuGrantTransferResource().build(); when(euGrantTransferRepository.findByApplicationId(applicationId)).thenReturn(grantTransfer); when(mapper.mapToResource(grantTransfer)).thenReturn(grantTransferResource); ServiceResult<EuGrantTransferResource> result = service.getGrantTransferByApplicationId(applicationId); assertTrue(result.isSuccess()); assertEquals(result.getSuccess(), grantTransferResource); }
### Question: AuthenticationRequestWrapper extends HttpServletRequestWrapper { @Override public ServletInputStream getInputStream() throws IOException { ByteArrayInputStream inputStream = new ByteArrayInputStream(body.getBytes()); return new ServletInputStream() { @Override public boolean isFinished() { return inputStream.available() == 0; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener listener) { throw new IllegalStateException("Not implemented"); } @Override public int read() throws IOException { return inputStream.read(); } }; } AuthenticationRequestWrapper(HttpServletRequest request); @Override ServletInputStream getInputStream(); @Override BufferedReader getReader(); }### Answer: @Test public void getInputStream() throws Exception { ServletInputStream first = authenticationRequestWrapper.getInputStream(); assertEquals("First call to getInputStream should match request content", content, IOUtils.toString(first, "UTF-8")); ServletInputStream second = authenticationRequestWrapper.getInputStream(); assertEquals("Subsequent calls to getInputStream should match request content", content, IOUtils.toString(second, "UTF-8")); }
### Question: AuthenticationRequestWrapper extends HttpServletRequestWrapper { @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(this.getInputStream())); } AuthenticationRequestWrapper(HttpServletRequest request); @Override ServletInputStream getInputStream(); @Override BufferedReader getReader(); }### Answer: @Test public void getReader() throws Exception { Reader first = authenticationRequestWrapper.getReader(); assertEquals("First call to getInputStream should match request content", content, IOUtils.toString(first)); Reader second = authenticationRequestWrapper.getReader(); assertEquals("Subsequent calls to getInputStream should match request content", content, IOUtils.toString(second)); }
### Question: TokenAuthenticationService { public AuthenticationToken getAuthentication(HttpServletRequest request) { if (isHashValidForRequest(request)) { return new AuthenticationToken(); } return null; } @Autowired TokenAuthenticationService(@Value("${ifs.finance-totals.authSecretKey}") String secretKey, HashBasedMacTokenHandler tokenHandler); AuthenticationToken getAuthentication(HttpServletRequest request); }### Answer: @Test public void getAuthentication() throws Exception { String token = "f6d99caceac489fd2d4ba8106d15e64bd7455fd83305f13a7faa32fb3b02fa28"; MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); httpServletRequest.addHeader("X-AUTH-TOKEN", token); httpServletRequest.setContent("input".getBytes()); assertNotNull(tokenAuthenticationService.getAuthentication(httpServletRequest)); } @Test public void getAuthentication_notAuthenticated() throws Exception { String token = "incorrect-hash"; MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); httpServletRequest.addHeader("X-AUTH-TOKEN", token); httpServletRequest.setContent("input".getBytes()); assertNull(tokenAuthenticationService.getAuthentication(httpServletRequest)); } @Test public void getAuthentication_missingContent() throws Exception { MockHttpServletRequest httpServletRequest = new MockHttpServletRequest(); assertNull(tokenAuthenticationService.getAuthentication(httpServletRequest)); }
### Question: CostTotalController { @PostMapping("/cost-total") public RestResult<Void> addCostTotal(@NotNull @RequestBody FinanceCostTotalResource financeCostTotalResource) { return costTotalService.saveCostTotal(financeCostTotalResource).toPostCreateResponse(); } @Autowired CostTotalController(CostTotalService costTotalService); @PostMapping("/cost-total") RestResult<Void> addCostTotal(@NotNull @RequestBody FinanceCostTotalResource financeCostTotalResource); @PostMapping("/cost-totals") RestResult<Void> addCostTotals(@NotNull @RequestBody List<FinanceCostTotalResource> financeCostTotalResources); }### Answer: @Test public void addCostTotal() throws Exception { FinanceCostTotalResource financeCostTotalResource = new FinanceCostTotalResource( FinanceType.APPLICATION, FinanceRowType.LABOUR, new BigDecimal("999999999.999999"), 1L ); Consumer<FinanceCostTotalResource> matchesExpectedResource = (resource) -> { assertThat(resource).isEqualToComparingFieldByField(financeCostTotalResource); }; when(costTotalService.saveCostTotal(createLambdaMatcher(matchesExpectedResource))).thenReturn(serviceSuccess()); mockMvc.perform( post("/cost-total") .content(json(financeCostTotalResource)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isCreated()); verify(costTotalService).saveCostTotal(createLambdaMatcher(matchesExpectedResource)); }
### Question: CostTotalController { @PostMapping("/cost-totals") public RestResult<Void> addCostTotals(@NotNull @RequestBody List<FinanceCostTotalResource> financeCostTotalResources) { LOG.debug("Initiating addCostTotals for financeIds: {}", financeCostTotalResources.stream().map(financeCostTotalResource -> String.valueOf(financeCostTotalResource.getFinanceId())) .collect(Collectors.joining(", "))); return costTotalService.saveCostTotals(financeCostTotalResources).toPostCreateResponse(); } @Autowired CostTotalController(CostTotalService costTotalService); @PostMapping("/cost-total") RestResult<Void> addCostTotal(@NotNull @RequestBody FinanceCostTotalResource financeCostTotalResource); @PostMapping("/cost-totals") RestResult<Void> addCostTotals(@NotNull @RequestBody List<FinanceCostTotalResource> financeCostTotalResources); }### Answer: @Test public void addCostTotals() throws Exception { List<FinanceCostTotalResource> financeCostTotalResources = newFinanceCostTotalResource() .withFinanceType(FinanceType.APPLICATION) .withFinanceRowType(FinanceRowType.LABOUR, FinanceRowType.MATERIALS) .withFinanceId(1L, 2L) .withTotal(new BigDecimal("999.999999"), new BigDecimal("1999.999999")) .build(2); Consumer<List<FinanceCostTotalResource>> matchesExpectedResources = (resources) -> { assertThat(resources).usingFieldByFieldElementComparator().containsAll(financeCostTotalResources); }; when(costTotalService.saveCostTotals(createLambdaMatcher(matchesExpectedResources))).thenReturn(serviceSuccess()); mockMvc.perform( post("/cost-totals") .content(json(financeCostTotalResources)) .contentType(MediaType.APPLICATION_JSON) ) .andExpect(status().isCreated()); verify(costTotalService).saveCostTotals(createLambdaMatcher(matchesExpectedResources)); }
### Question: HashBasedMacTokenHandler { public String calculateHash(String key, String input) throws InvalidKeyException { Mac mac; try { mac = Mac.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Failed to initialise MAC object: " + e.getMessage(), e); } mac.init(getKey(key)); return Hex.encodeHexString(mac.doFinal(getInputAsByteArray(input))); } String calculateHash(String key, String input); }### Answer: @Test public void calculateHash() throws Exception { assertEquals("f6d99caceac489fd2d4ba8106d15e64bd7455fd83305f13a7faa32fb3b02fa28", hashBasedMacTokenHandler.calculateHash("supersecretkey", "input")); } @Test(expected = IllegalArgumentException.class) public void calculateHash_nullKey() throws Exception { hashBasedMacTokenHandler.calculateHash(null, "input"); } @Test(expected = IllegalArgumentException.class) public void calculateHash_emptyKey() throws Exception { hashBasedMacTokenHandler.calculateHash("", "input"); } @Test public void calculateHash_nullData() throws Exception { assertEquals("c46ebcad47b875a746029ac6c2f8636ffd012d2b3cd524d77f2d813b5b74f589", hashBasedMacTokenHandler.calculateHash("supersecretkey", null)); } @Test public void calculateHash_emptyData() throws Exception { assertEquals("c46ebcad47b875a746029ac6c2f8636ffd012d2b3cd524d77f2d813b5b74f589", hashBasedMacTokenHandler.calculateHash("supersecretkey", "")); }
### Question: AlertPermissionRules { @PermissionRule(value = "CREATE", description = "System maintentenance users can create Alerts") public boolean systemMaintenanceUserCanCreateAlerts(final AlertResource alertResource, final UserResource user) { return isSystemMaintenanceUser(user); } @PermissionRule(value = "CREATE", description = "System maintentenance users can create Alerts") boolean systemMaintenanceUserCanCreateAlerts(final AlertResource alertResource, final UserResource user); @PermissionRule(value = "DELETE", description = "System maintentenance users can delete Alerts") boolean systemMaintenanceUserCanDeleteAlerts(final AlertResource alertResource, final UserResource user); }### Answer: @Test public void systemMaintenanceUserCanCreateAlerts() throws Exception { assertTrue(rules.systemMaintenanceUserCanCreateAlerts(alertResource, systemMaintenanceUser())); } @Test public void systemMaintenanceUserCanCreateAlerts_anonymous() throws Exception { assertFalse(rules.systemMaintenanceUserCanCreateAlerts(alertResource, anonymousUser())); }
### Question: AlertPermissionRules { @PermissionRule(value = "DELETE", description = "System maintentenance users can delete Alerts") public boolean systemMaintenanceUserCanDeleteAlerts(final AlertResource alertResource, final UserResource user) { return isSystemMaintenanceUser(user); } @PermissionRule(value = "CREATE", description = "System maintentenance users can create Alerts") boolean systemMaintenanceUserCanCreateAlerts(final AlertResource alertResource, final UserResource user); @PermissionRule(value = "DELETE", description = "System maintentenance users can delete Alerts") boolean systemMaintenanceUserCanDeleteAlerts(final AlertResource alertResource, final UserResource user); }### Answer: @Test public void systemMaintenanceUserCanDeleteAlerts() throws Exception { assertTrue(rules.systemMaintenanceUserCanDeleteAlerts(alertResource, systemMaintenanceUser())); } @Test public void systemMaintenanceUserCanDeleteAlerts_anonymous() throws Exception { assertFalse(rules.systemMaintenanceUserCanDeleteAlerts(alertResource, anonymousUser())); }
### Question: AlertController { @GetMapping("/find-all-visible") public RestResult<List<AlertResource>> findAllVisible() { return alertService.findAllVisible().toGetResponse(); } @GetMapping("/find-all-visible") RestResult<List<AlertResource>> findAllVisible(); @GetMapping("/find-all-visible/{type}") RestResult<List<AlertResource>> findAllVisibleByType(@PathVariable("type") AlertType type); @GetMapping("/{id}") RestResult<AlertResource> findById(@PathVariable("id") Long id); @PostMapping("/") RestResult<AlertResource> create(@RequestBody AlertResource alertResource); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @DeleteMapping("/delete/{type}") RestResult<Void> deleteAllByType(@PathVariable("type") AlertType type); }### Answer: @Test public void test_findAllVisible() throws Exception { final AlertResource expected1 = AlertResourceBuilder.newAlertResource() .withId(8888L) .build(); final AlertResource expected2 = AlertResourceBuilder.newAlertResource() .withId(9999L) .build(); final List<AlertResource> expected = new ArrayList<>(asList(expected1, expected2)); when(alertServiceMock.findAllVisible()).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/alert/find-all-visible")) .andExpect(status().isOk()) .andExpect(jsonPath("[0]id", is(8888))) .andExpect(jsonPath("[1]id", is(9999))) .andDo(document("alert/find-all-visible", pathParameters( ), responseFields( fieldWithPath("[]").description("An array of the alerts which are visible") ).andWithPrefix("[].", AlertDocs.alertResourceFields)) ); }
### Question: AlertController { @GetMapping("/find-all-visible/{type}") public RestResult<List<AlertResource>> findAllVisibleByType(@PathVariable("type") AlertType type) { return alertService.findAllVisibleByType(type).toGetResponse(); } @GetMapping("/find-all-visible") RestResult<List<AlertResource>> findAllVisible(); @GetMapping("/find-all-visible/{type}") RestResult<List<AlertResource>> findAllVisibleByType(@PathVariable("type") AlertType type); @GetMapping("/{id}") RestResult<AlertResource> findById(@PathVariable("id") Long id); @PostMapping("/") RestResult<AlertResource> create(@RequestBody AlertResource alertResource); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @DeleteMapping("/delete/{type}") RestResult<Void> deleteAllByType(@PathVariable("type") AlertType type); }### Answer: @Test public void test_findAllVisibleByType() throws Exception { final AlertResource expected1 = AlertResourceBuilder.newAlertResource() .withId(8888L) .build(); final AlertResource expected2 = AlertResourceBuilder.newAlertResource() .withId(9999L) .build(); final List<AlertResource> expected = new ArrayList<>(asList(expected1, expected2)); when(alertServiceMock.findAllVisibleByType(MAINTENANCE)).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/alert/find-all-visible/{type}", MAINTENANCE.name())) .andExpect(status().isOk()) .andExpect(jsonPath("[0]id", is(8888))) .andExpect(jsonPath("[1]id", is(9999))) .andDo(document("alert/find-all-visible-by-type", pathParameters( parameterWithName("type").description("Type of alert to find") ),responseFields( fieldWithPath("[]").description("An array of the alerts of the specified type which are visible") ).andWithPrefix("[].", AlertDocs.alertResourceFields)) ); }
### Question: AlertController { @GetMapping("/{id}") public RestResult<AlertResource> findById(@PathVariable("id") Long id) { return alertService.findById(id).toGetResponse(); } @GetMapping("/find-all-visible") RestResult<List<AlertResource>> findAllVisible(); @GetMapping("/find-all-visible/{type}") RestResult<List<AlertResource>> findAllVisibleByType(@PathVariable("type") AlertType type); @GetMapping("/{id}") RestResult<AlertResource> findById(@PathVariable("id") Long id); @PostMapping("/") RestResult<AlertResource> create(@RequestBody AlertResource alertResource); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @DeleteMapping("/delete/{type}") RestResult<Void> deleteAllByType(@PathVariable("type") AlertType type); }### Answer: @Test public void test_getById() throws Exception { final AlertResource expected = AlertResourceBuilder.newAlertResource() .withId(9999L) .build(); when(alertServiceMock.findById(9999L)).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/alert/{id}", 9999L)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(expected))) .andDo(document("alert/find-by-id", pathParameters( parameterWithName("id").description("Id of the alert to find") ), PayloadDocumentation.responseFields(AlertDocs.alertResourceFields)) ); }
### Question: AlertController { @PostMapping("/") public RestResult<AlertResource> create(@RequestBody AlertResource alertResource) { return alertService.create(alertResource).toPostCreateResponse(); } @GetMapping("/find-all-visible") RestResult<List<AlertResource>> findAllVisible(); @GetMapping("/find-all-visible/{type}") RestResult<List<AlertResource>> findAllVisibleByType(@PathVariable("type") AlertType type); @GetMapping("/{id}") RestResult<AlertResource> findById(@PathVariable("id") Long id); @PostMapping("/") RestResult<AlertResource> create(@RequestBody AlertResource alertResource); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @DeleteMapping("/delete/{type}") RestResult<Void> deleteAllByType(@PathVariable("type") AlertType type); }### Answer: @Test public void test_create() throws Exception { final AlertResource alertResource = AlertResourceBuilder.newAlertResource() .build(); final AlertResource expected = AlertResourceBuilder.newAlertResource() .withId(9999L) .build(); when(alertServiceMock.create(alertResource)).thenReturn(serviceSuccess(expected)); mockMvc.perform(post("/alert/") .contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsString(alertResource))) .andExpect(status().isCreated()) .andExpect(content().string(objectMapper.writeValueAsString(expected))) .andDo(document("alert/create", PayloadDocumentation.requestFields(AlertDocs.alertResourceFields), PayloadDocumentation.responseFields(AlertDocs.alertResourceFields)) ); }
### Question: AlertController { @DeleteMapping("/{id}") public RestResult<Void> delete(@PathVariable("id") Long id) { return alertService.delete(id).toDeleteResponse(); } @GetMapping("/find-all-visible") RestResult<List<AlertResource>> findAllVisible(); @GetMapping("/find-all-visible/{type}") RestResult<List<AlertResource>> findAllVisibleByType(@PathVariable("type") AlertType type); @GetMapping("/{id}") RestResult<AlertResource> findById(@PathVariable("id") Long id); @PostMapping("/") RestResult<AlertResource> create(@RequestBody AlertResource alertResource); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @DeleteMapping("/delete/{type}") RestResult<Void> deleteAllByType(@PathVariable("type") AlertType type); }### Answer: @Test public void test_delete() throws Exception { when(alertServiceMock.delete(9999L)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/alert/{id}", 9999L)) .andExpect(status().isNoContent()) .andExpect(content().string(isEmptyString())) .andDo(document("alert/delete", pathParameters( parameterWithName("id").description("Id of the alert to be deleted") )) ); }
### Question: AlertServiceImpl extends RootTransactionalService implements AlertService { @Override public ServiceResult<List<AlertResource>> findAllVisible() { return serviceSuccess(simpleMap(alertRepository.findAllVisible(now()), alertMapper::mapToResource)); } @Override ServiceResult<List<AlertResource>> findAllVisible(); @Override ServiceResult<List<AlertResource>> findAllVisibleByType(AlertType type); @Override ServiceResult<AlertResource> findById(Long id); @Override @Transactional ServiceResult<AlertResource> create(AlertResource alertResource); @Override @Transactional ServiceResult<Void> delete(Long id); @Override @Transactional ServiceResult<Void> deleteAllByType(AlertType type); }### Answer: @Test public void findAllVisible() throws Exception { final Alert alert1 = new Alert(); final Alert alert2 = new Alert(); final List<Alert> alerts = new ArrayList<>(asList(alert1, alert2)); final AlertResource expected1 = AlertResourceBuilder.newAlertResource() .build(); final AlertResource expected2 = AlertResourceBuilder.newAlertResource() .build(); when(alertRepositoryMock.findAllVisible(isA(ZonedDateTime.class))).thenReturn(alerts); when(alertMapperMock.mapToResource(same(alert1))).thenReturn(expected1); when(alertMapperMock.mapToResource(same(alert2))).thenReturn(expected2); final List<AlertResource> found = alertService.findAllVisible().getSuccess(); assertSame(expected1, found.get(0)); assertSame(expected2, found.get(1)); verify(alertRepositoryMock, only()).findAllVisible(isA(ZonedDateTime.class)); }
### Question: AlertServiceImpl extends RootTransactionalService implements AlertService { @Override public ServiceResult<List<AlertResource>> findAllVisibleByType(AlertType type) { return serviceSuccess(simpleMap(alertRepository.findAllVisibleByType(type, now()), alertMapper::mapToResource)); } @Override ServiceResult<List<AlertResource>> findAllVisible(); @Override ServiceResult<List<AlertResource>> findAllVisibleByType(AlertType type); @Override ServiceResult<AlertResource> findById(Long id); @Override @Transactional ServiceResult<AlertResource> create(AlertResource alertResource); @Override @Transactional ServiceResult<Void> delete(Long id); @Override @Transactional ServiceResult<Void> deleteAllByType(AlertType type); }### Answer: @Test public void findAllVisibleByType() throws Exception { final Alert alert1 = new Alert(); final Alert alert2 = new Alert(); final List<Alert> alerts = new ArrayList<>(asList(alert1, alert2)); final AlertResource expected1 = AlertResourceBuilder.newAlertResource() .build(); final AlertResource expected2 = AlertResourceBuilder.newAlertResource() .build(); when(alertRepositoryMock.findAllVisibleByType(same(MAINTENANCE), isA(ZonedDateTime.class))).thenReturn(alerts); when(alertMapperMock.mapToResource(same(alert1))).thenReturn(expected1); when(alertMapperMock.mapToResource(same(alert2))).thenReturn(expected2); final List<AlertResource> found = alertService.findAllVisibleByType(MAINTENANCE).getSuccess(); assertSame(expected1, found.get(0)); assertSame(expected2, found.get(1)); verify(alertRepositoryMock, only()).findAllVisibleByType(same(MAINTENANCE), isA(ZonedDateTime.class)); }
### Question: AlertServiceImpl extends RootTransactionalService implements AlertService { @Override public ServiceResult<AlertResource> findById(Long id) { return find(alertRepository.findById(id), notFoundError(Alert.class, id)).andOnSuccessReturn(alertMapper::mapToResource); } @Override ServiceResult<List<AlertResource>> findAllVisible(); @Override ServiceResult<List<AlertResource>> findAllVisibleByType(AlertType type); @Override ServiceResult<AlertResource> findById(Long id); @Override @Transactional ServiceResult<AlertResource> create(AlertResource alertResource); @Override @Transactional ServiceResult<Void> delete(Long id); @Override @Transactional ServiceResult<Void> deleteAllByType(AlertType type); }### Answer: @Test public void findById() throws Exception { final AlertResource expected = AlertResourceBuilder.newAlertResource() .build(); final Alert alert = new Alert(); when(alertRepositoryMock.findById(9999L)).thenReturn(Optional.of(alert)); when(alertMapperMock.mapToResource(same(alert))).thenReturn(expected); assertSame(expected, alertService.findById(9999L).getSuccess()); verify(alertRepositoryMock, only()).findById(9999L); }
### Question: AlertServiceImpl extends RootTransactionalService implements AlertService { @Override @Transactional public ServiceResult<AlertResource> create(AlertResource alertResource) { Alert saved = alertRepository.save(alertMapper.mapToDomain(alertResource)); return serviceSuccess(alertMapper.mapToResource(saved)); } @Override ServiceResult<List<AlertResource>> findAllVisible(); @Override ServiceResult<List<AlertResource>> findAllVisibleByType(AlertType type); @Override ServiceResult<AlertResource> findById(Long id); @Override @Transactional ServiceResult<AlertResource> create(AlertResource alertResource); @Override @Transactional ServiceResult<Void> delete(Long id); @Override @Transactional ServiceResult<Void> deleteAllByType(AlertType type); }### Answer: @Test public void create() throws Exception { final AlertResource alertResource = AlertResourceBuilder.newAlertResource() .build(); final AlertResource expected = AlertResourceBuilder.newAlertResource() .build(); final Alert alert = new Alert(); when(alertMapperMock.mapToDomain(same(alertResource))).thenReturn(alert); when(alertRepositoryMock.save(same(alert))).thenReturn(alert); when(alertMapperMock.mapToResource(same(alert))).thenReturn(expected); assertSame(expected, alertService.create(alertResource).getSuccess()); verify(alertRepositoryMock, only()).save(alert); }
### Question: AlertServiceImpl extends RootTransactionalService implements AlertService { @Override @Transactional public ServiceResult<Void> delete(Long id) { alertRepository.deleteById(id); return serviceSuccess(); } @Override ServiceResult<List<AlertResource>> findAllVisible(); @Override ServiceResult<List<AlertResource>> findAllVisibleByType(AlertType type); @Override ServiceResult<AlertResource> findById(Long id); @Override @Transactional ServiceResult<AlertResource> create(AlertResource alertResource); @Override @Transactional ServiceResult<Void> delete(Long id); @Override @Transactional ServiceResult<Void> deleteAllByType(AlertType type); }### Answer: @Test public void delete() throws Exception { assertTrue(alertService.delete(9999L).isSuccess()); verify(alertRepositoryMock, only()).deleteById(9999L); }
### Question: AlertServiceImpl extends RootTransactionalService implements AlertService { @Override @Transactional public ServiceResult<Void> deleteAllByType(AlertType type) { alertRepository.deleteByType(type); return serviceSuccess(); } @Override ServiceResult<List<AlertResource>> findAllVisible(); @Override ServiceResult<List<AlertResource>> findAllVisibleByType(AlertType type); @Override ServiceResult<AlertResource> findById(Long id); @Override @Transactional ServiceResult<AlertResource> create(AlertResource alertResource); @Override @Transactional ServiceResult<Void> delete(Long id); @Override @Transactional ServiceResult<Void> deleteAllByType(AlertType type); }### Answer: @Test public void deleteAllByType() throws Exception { assertTrue(alertService.delete(9999L).isSuccess()); }
### Question: PasswordValidator implements Validator<String, InvalidPasswordException> { @Override public void validate(final String password) throws InvalidPasswordException { final String passwordLowerCase = password.toLowerCase(); if(passwordPolicy.getBlacklist().stream().anyMatch(passwordLowerCase::contains)) { throw new InvalidPasswordException(singletonList(InvalidPasswordException.ERROR_KEY)); } } PasswordValidator(final PasswordPolicyProperties passwordPolicy); @Override void validate(final String password); }### Answer: @Test public void shouldAcceptValidPasswords() throws InvalidPasswordException { validator.validate("valid-password"); } @Test public void shouldRejectDuplicateEmails() { try { validator.validate("invalid-password"); assertThat("Service failed to throw expected exception.", false); } catch (final InvalidPasswordException exception) { assertThat(exception.toErrorResponse().getKey(), is(equalTo(InvalidPasswordException.ERROR_KEY))); assertThat(exception.toErrorResponse().getArguments(), hasItem(equalTo(InvalidPasswordException.ERROR_KEY))); } }
### Question: EmailValidator implements Validator<String, DuplicateEmailException> { @Override public void validate(final String email) throws DuplicateEmailException { final Optional<Identity> byEmail = findIdentityService.findByEmail(email); if (byEmail.isPresent()) { throw new DuplicateEmailException(); } } EmailValidator(final FindIdentityService findIdentityService); @Override void validate(final String email); }### Answer: @Test public void shouldAcceptValidEmails() throws DuplicateEmailException { when(findIdentityService.findByEmail(eq("[email protected]"))).thenReturn(Optional.empty()); validator.validate("[email protected]"); verify(findIdentityService).findByEmail(eq("[email protected]")); verifyNoMoreInteractions(findIdentityService); } @Test public void shouldRejectDuplicateEmails() { when(findIdentityService.findByEmail(eq("[email protected]"))).thenReturn(Optional.of(new Identity())); try { validator.validate("[email protected]"); assertThat("Service failed to throw expected exception.", false); } catch (final DuplicateEmailException exception) { assertThat(exception.toErrorResponse().getKey(), is(equalTo("DUPLICATE_EMAIL_ADDRESS"))); assertThat(exception.toErrorResponse().getArguments(), is(emptyCollectionOf(String.class))); } verify(findIdentityService).findByEmail(eq("[email protected]")); verifyNoMoreInteractions(findIdentityService); }
### Question: AgreementRestServiceImpl extends BaseRestService implements AgreementRestService { @Override public RestResult<AgreementResource> getCurrentAgreement() { return getWithRestResult(agreementRestURL + "/find-current", AgreementResource.class); } @Override RestResult<AgreementResource> getCurrentAgreement(); }### Answer: @Test public void getCurrentContract() { AgreementResource agreementResource = new AgreementResource(); setupGetWithRestResultExpectations(agreementUrl + "/find-current", AgreementResource.class, agreementResource, OK); RestResult<AgreementResource> result = service.getCurrentAgreement(); assertEquals(agreementResource, result.getSuccess()); }
### Question: KnowledgeBaseRestServiceImpl extends BaseRestService implements KnowledgeBaseRestService { @Override public RestResult<List<String>> getKnowledgeBases() { return getWithRestResultAnonymous(ORGANISATION_BASE_URL, stringsListType()); } @Override RestResult<List<String>> getKnowledgeBases(); @Override RestResult<KnowledgeBaseResource> getKnowledgeBaseByName(String knowledgeBaseName); }### Answer: @Test public void getKnowledgeBases() { String expected = "KnowledgeBase 1"; setupGetWithRestResultAnonymousExpectations(ORGANISATION_BASE_URL, stringsListType(), Collections.singletonList(expected), OK); RestResult<List<String>> result = service.getKnowledgeBases(); assertEquals(expected, result.getSuccess().get(0)); }
### Question: KnowledgeBaseRestServiceImpl extends BaseRestService implements KnowledgeBaseRestService { @Override public RestResult<KnowledgeBaseResource> getKnowledgeBaseByName(String knowledgeBaseName) { return getWithRestResultAnonymous(ORGANISATION_BASE_URL + "/find-by-name/" + knowledgeBaseName, KnowledgeBaseResource.class); } @Override RestResult<List<String>> getKnowledgeBases(); @Override RestResult<KnowledgeBaseResource> getKnowledgeBaseByName(String knowledgeBaseName); }### Answer: @Test public void getKnowledgeBaseByName() { String expected = "KnowledgeBase 1"; KnowledgeBaseResource knowledgeBaseResource = new KnowledgeBaseResource(); knowledgeBaseResource.setName(expected); setupGetWithRestResultAnonymousExpectations(ORGANISATION_BASE_URL + "/find-by-name/" + expected, KnowledgeBaseResource.class, knowledgeBaseResource, OK); RestResult<KnowledgeBaseResource> result = service.getKnowledgeBaseByName(expected); assertEquals(expected, result.getSuccess().getName()); }
### Question: FormInputRestServiceImpl extends BaseRestService implements FormInputRestService { @Override public RestResult<List<FormInputResource>> getByQuestionIdAndScope(Long questionId, FormInputScope scope) { return getWithRestResult(formInputRestURL + "/find-by-question-id/" + questionId + "/scope/" + scope, formInputResourceListType()); } @Override RestResult<FormInputResource> getById(Long formInputId); @Override RestResult<List<FormInputResource>> getByQuestionId(Long questionId); @Override RestResult<List<FormInputResource>> getByQuestionIdAndScope(Long questionId, FormInputScope scope); @Override RestResult<List<FormInputResource>> getByCompetitionId(Long competitionId); @Override RestResult<List<FormInputResource>> getByCompetitionIdAndScope(Long competitionId, FormInputScope scope); @Override RestResult<Void> delete(Long formInputId); @Override RestResult<ByteArrayResource> downloadFile(long formInputId); @Override RestResult<FileEntryResource> findFile(long formInputId); }### Answer: @Test public void testGetByQuestionIdAndScope() throws Exception { List<FormInputResource> expected = Stream.of(1, 2, 3).map(i -> new FormInputResource()).collect(Collectors.toList()); Long questionId = 1L; FormInputScope scope = FormInputScope.APPLICATION; setupGetWithRestResultExpectations(String.format("%s/find-by-question-id/%s/scope/%s", formInputRestUrl, questionId, scope), formInputResourceListType(), expected, OK); List<FormInputResource> response = service.getByQuestionIdAndScope(questionId, scope).getSuccess(); assertSame(expected, response); }
### Question: FormInputRestServiceImpl extends BaseRestService implements FormInputRestService { @Override public RestResult<List<FormInputResource>> getByCompetitionIdAndScope(Long competitionId, FormInputScope scope) { return getWithRestResult(formInputRestURL + "/find-by-competition-id/" + competitionId + "/scope/" + scope, formInputResourceListType()); } @Override RestResult<FormInputResource> getById(Long formInputId); @Override RestResult<List<FormInputResource>> getByQuestionId(Long questionId); @Override RestResult<List<FormInputResource>> getByQuestionIdAndScope(Long questionId, FormInputScope scope); @Override RestResult<List<FormInputResource>> getByCompetitionId(Long competitionId); @Override RestResult<List<FormInputResource>> getByCompetitionIdAndScope(Long competitionId, FormInputScope scope); @Override RestResult<Void> delete(Long formInputId); @Override RestResult<ByteArrayResource> downloadFile(long formInputId); @Override RestResult<FileEntryResource> findFile(long formInputId); }### Answer: @Test public void testGetByCompetitionIdAndScope() throws Exception { List<FormInputResource> expected = Stream.of(1, 2, 3).map(i -> new FormInputResource()).collect(Collectors.toList()); Long competitionId = 1L; FormInputScope scope = FormInputScope.APPLICATION; setupGetWithRestResultExpectations(String.format("%s/find-by-competition-id/%s/scope/%s", formInputRestUrl, competitionId, scope), formInputResourceListType(), expected, OK); List<FormInputResource> response = service.getByCompetitionIdAndScope(competitionId, scope).getSuccess(); assertSame(expected, response); }
### Question: FormInputRestServiceImpl extends BaseRestService implements FormInputRestService { @Override public RestResult<Void> delete(Long formInputId) { return deleteWithRestResult(formInputRestURL + "/" + formInputId, Void.class) ; } @Override RestResult<FormInputResource> getById(Long formInputId); @Override RestResult<List<FormInputResource>> getByQuestionId(Long questionId); @Override RestResult<List<FormInputResource>> getByQuestionIdAndScope(Long questionId, FormInputScope scope); @Override RestResult<List<FormInputResource>> getByCompetitionId(Long competitionId); @Override RestResult<List<FormInputResource>> getByCompetitionIdAndScope(Long competitionId, FormInputScope scope); @Override RestResult<Void> delete(Long formInputId); @Override RestResult<ByteArrayResource> downloadFile(long formInputId); @Override RestResult<FileEntryResource> findFile(long formInputId); }### Answer: @Test public void testDelete() throws Exception { Long formInputId = 1L; ResponseEntity<Void> result = setupDeleteWithRestResultExpectations(formInputRestUrl + "/" + formInputId); assertEquals(NO_CONTENT, result.getStatusCode()); }
### Question: GoogleAnalyticsDataLayerRestServiceImpl extends BaseRestService implements GoogleAnalyticsDataLayerRestService { @Override public RestResult<String> getCompetitionNameForApplication(long applicationId) { return getWithRestResult(format("%s/application/%d/competition-name", ANALYTICS_BASE_URL, applicationId), String.class ); } @Override RestResult<String> getCompetitionNameForInvite(String inviteHash); @Override RestResult<String> getCompetitionNameForApplication(long applicationId); @Override RestResult<String> getCompetitionName(long competitionId); @Override RestResult<String> getCompetitionNameForProject(long projectId); @Override RestResult<String> getCompetitionNameForAssessment(long assessmentId); @Override RestResult<List<Role>> getRolesByApplicationId(long applicationId); @Override RestResult<List<Role>> getRolesByProjectId(long projectId); @Override RestResult<Long> getApplicationIdForProject(long projectId); @Override RestResult<Long> getApplicationIdForAssessment(long assessmentId); }### Answer: @Test public void getCompetitionNameForApplication() { long applicationId = 5L; String expected = "competition name"; setupGetWithRestResultExpectations( format("%s/%s/%d/competition-name", restUrl, "application", applicationId), String.class, expected ); String actual = service.getCompetitionNameForApplication(applicationId).getSuccess(); assertEquals(expected, actual); }
### Question: GoogleAnalyticsDataLayerRestServiceImpl extends BaseRestService implements GoogleAnalyticsDataLayerRestService { @Override public RestResult<String> getCompetitionName(long competitionId) { return getWithRestResultAnonymous(format("%s/competition/%d/competition-name", ANALYTICS_BASE_URL, competitionId), String.class); } @Override RestResult<String> getCompetitionNameForInvite(String inviteHash); @Override RestResult<String> getCompetitionNameForApplication(long applicationId); @Override RestResult<String> getCompetitionName(long competitionId); @Override RestResult<String> getCompetitionNameForProject(long projectId); @Override RestResult<String> getCompetitionNameForAssessment(long assessmentId); @Override RestResult<List<Role>> getRolesByApplicationId(long applicationId); @Override RestResult<List<Role>> getRolesByProjectId(long projectId); @Override RestResult<Long> getApplicationIdForProject(long projectId); @Override RestResult<Long> getApplicationIdForAssessment(long assessmentId); }### Answer: @Test public void getCompetitionName() { long competitionId = 7L; String expected = "competition name"; setupGetWithRestResultAnonymousExpectations( format("%s/%s/%d/competition-name", restUrl, "competition", competitionId), String.class, expected ); String actual = service.getCompetitionName(competitionId).getSuccess(); assertEquals(expected, actual); }
### Question: GoogleAnalyticsDataLayerRestServiceImpl extends BaseRestService implements GoogleAnalyticsDataLayerRestService { @Override public RestResult<String> getCompetitionNameForProject(long projectId) { return getWithRestResult(format("%s/project/%d/competition-name", ANALYTICS_BASE_URL, projectId), String.class); } @Override RestResult<String> getCompetitionNameForInvite(String inviteHash); @Override RestResult<String> getCompetitionNameForApplication(long applicationId); @Override RestResult<String> getCompetitionName(long competitionId); @Override RestResult<String> getCompetitionNameForProject(long projectId); @Override RestResult<String> getCompetitionNameForAssessment(long assessmentId); @Override RestResult<List<Role>> getRolesByApplicationId(long applicationId); @Override RestResult<List<Role>> getRolesByProjectId(long projectId); @Override RestResult<Long> getApplicationIdForProject(long projectId); @Override RestResult<Long> getApplicationIdForAssessment(long assessmentId); }### Answer: @Test public void getCompetitionNameForProject() { long projectId = 11L; String expected = "competition name"; setupGetWithRestResultExpectations( format("%s/%s/%d/competition-name", restUrl, "project", projectId), String.class, expected ); String actual = service.getCompetitionNameForProject(projectId).getSuccess(); assertEquals(expected, actual); }
### Question: GoogleAnalyticsDataLayerRestServiceImpl extends BaseRestService implements GoogleAnalyticsDataLayerRestService { @Override public RestResult<String> getCompetitionNameForAssessment(long assessmentId) { return getWithRestResult(format("%s/assessment/%d/competition-name", ANALYTICS_BASE_URL, assessmentId), String.class ); } @Override RestResult<String> getCompetitionNameForInvite(String inviteHash); @Override RestResult<String> getCompetitionNameForApplication(long applicationId); @Override RestResult<String> getCompetitionName(long competitionId); @Override RestResult<String> getCompetitionNameForProject(long projectId); @Override RestResult<String> getCompetitionNameForAssessment(long assessmentId); @Override RestResult<List<Role>> getRolesByApplicationId(long applicationId); @Override RestResult<List<Role>> getRolesByProjectId(long projectId); @Override RestResult<Long> getApplicationIdForProject(long projectId); @Override RestResult<Long> getApplicationIdForAssessment(long assessmentId); }### Answer: @Test public void getCompetitionNameForAssessment() { long assessmentId = 13L; String expected = "competition name"; setupGetWithRestResultExpectations( format("%s/%s/%d/competition-name", restUrl, "assessment", assessmentId), String.class, expected ); String actual = service.getCompetitionNameForAssessment(assessmentId).getSuccess(); assertEquals(expected, actual); }
### Question: GoogleAnalyticsDataLayerRestServiceImpl extends BaseRestService implements GoogleAnalyticsDataLayerRestService { @Override public RestResult<List<Role>> getRolesByApplicationId(long applicationId) { return getWithRestResult(format("%s/application/%d/user-roles", ANALYTICS_BASE_URL, applicationId), roleListType() ); } @Override RestResult<String> getCompetitionNameForInvite(String inviteHash); @Override RestResult<String> getCompetitionNameForApplication(long applicationId); @Override RestResult<String> getCompetitionName(long competitionId); @Override RestResult<String> getCompetitionNameForProject(long projectId); @Override RestResult<String> getCompetitionNameForAssessment(long assessmentId); @Override RestResult<List<Role>> getRolesByApplicationId(long applicationId); @Override RestResult<List<Role>> getRolesByProjectId(long projectId); @Override RestResult<Long> getApplicationIdForProject(long projectId); @Override RestResult<Long> getApplicationIdForAssessment(long assessmentId); }### Answer: @Test public void getApplicationRolesById() { long applicationId = 123L; List<Role> expectedRoles = singletonList(Role.COLLABORATOR); setupGetWithRestResultExpectations( format("%s/%s/%d/user-roles", restUrl, "application", applicationId), roleListType(), expectedRoles ); List<Role> roles = service.getRolesByApplicationId(applicationId).getSuccess(); assertEquals(expectedRoles, roles); }
### Question: RegistrationServiceImpl extends BaseTransactionalService implements RegistrationService { @Override @Transactional public ServiceResult<User> activatePendingUser(User user, String password, String hash) { if(monitoringOfficerInviteRepository.existsByHash(hash)) { return activateUser(user) .andOnSuccess(activatedUser -> idpService.updateUserPassword(activatedUser.getUid(), password)) .andOnSuccessReturn(() -> user); } return serviceFailure(GENERAL_NOT_FOUND); } @Override @Transactional ServiceResult<UserResource> createUser(UserCreationResource user); @Override @Transactional ServiceResult<Void> resendUserVerificationEmail(final UserResource user); @Override @Transactional @UserUpdate ServiceResult<UserResource> activateUser(long userId); @Override @Transactional @UserUpdate ServiceResult<UserResource> deactivateUser(long userId); @Override @Transactional ServiceResult<User> activatePendingUser(User user, String password, String hash); @Override @Transactional ServiceResult<Void> activateApplicantAndSendDiversitySurvey(long userId); @Override @Transactional ServiceResult<Void> activateAssessorAndSendDiversitySurvey(long userId); @Override @Transactional @UserUpdate ServiceResult<UserResource> editInternalUser(UserResource userToEdit, Role userRoleType); }### Answer: @Test public void activatePendingUser() { User user = newUser().withUid("uid").build(); when(monitoringOfficerInviteRepositoryMock.existsByHash("hash")).thenReturn(true); when(idpServiceMock.activateUser(anyString())).thenReturn(serviceSuccess("uid")); when(userRepositoryMock.save(any(User.class))).thenReturn(user); when(idpServiceMock.updateUserPassword("uid", "password")).thenReturn(serviceSuccess("uid")); service.activatePendingUser(user, "password", "hash").getSuccess(); verify(monitoringOfficerInviteRepositoryMock).existsByHash("hash"); verify(idpServiceMock).activateUser(anyString()); verify(userRepositoryMock).save(any(User.class)); verify(idpServiceMock).updateUserPassword("uid", "password"); }
### Question: GoogleAnalyticsDataLayerRestServiceImpl extends BaseRestService implements GoogleAnalyticsDataLayerRestService { @Override public RestResult<List<Role>> getRolesByProjectId(long projectId) { return getWithRestResult(format("%s/project/%d/user-roles", ANALYTICS_BASE_URL, projectId), roleListType()); } @Override RestResult<String> getCompetitionNameForInvite(String inviteHash); @Override RestResult<String> getCompetitionNameForApplication(long applicationId); @Override RestResult<String> getCompetitionName(long competitionId); @Override RestResult<String> getCompetitionNameForProject(long projectId); @Override RestResult<String> getCompetitionNameForAssessment(long assessmentId); @Override RestResult<List<Role>> getRolesByApplicationId(long applicationId); @Override RestResult<List<Role>> getRolesByProjectId(long projectId); @Override RestResult<Long> getApplicationIdForProject(long projectId); @Override RestResult<Long> getApplicationIdForAssessment(long assessmentId); }### Answer: @Test public void getProjectRolesById() { long projectId = 999L; List<Role> expectedRoles = asList(Role.PARTNER, Role.PROJECT_MANAGER); setupGetWithRestResultExpectations( format("%s/%s/%d/user-roles", restUrl, "project", projectId), roleListType(), expectedRoles ); List<Role> roles = service.getRolesByProjectId(projectId).getSuccess(); assertEquals(expectedRoles, roles); }
### Question: GoogleAnalyticsDataLayerRestServiceImpl extends BaseRestService implements GoogleAnalyticsDataLayerRestService { @Override public RestResult<Long> getApplicationIdForProject(long projectId) { return getWithRestResult(format("%s/project/%d/application-id", ANALYTICS_BASE_URL, projectId), Long.class); } @Override RestResult<String> getCompetitionNameForInvite(String inviteHash); @Override RestResult<String> getCompetitionNameForApplication(long applicationId); @Override RestResult<String> getCompetitionName(long competitionId); @Override RestResult<String> getCompetitionNameForProject(long projectId); @Override RestResult<String> getCompetitionNameForAssessment(long assessmentId); @Override RestResult<List<Role>> getRolesByApplicationId(long applicationId); @Override RestResult<List<Role>> getRolesByProjectId(long projectId); @Override RestResult<Long> getApplicationIdForProject(long projectId); @Override RestResult<Long> getApplicationIdForAssessment(long assessmentId); }### Answer: @Test public void getApplicationIdForProject() { long projectId = 987L; long applicationId = 654L; setupGetWithRestResultExpectations( format("%s/%s/%d/application-id", restUrl, "project", projectId), Long.class, applicationId ); long expectedApplicationId = service.getApplicationIdForProject(projectId).getSuccess(); assertEquals(expectedApplicationId, applicationId); }
### Question: SectionStatusRestServiceImpl extends BaseRestService implements SectionStatusRestService { @Override public RestResult<ValidationMessages> markAsComplete(long sectionId, long applicationId, long markedAsCompleteById) { return postWithRestResult(sectionRestURL + "/mark-as-complete/" + sectionId + "/" + applicationId + "/" + markedAsCompleteById, ValidationMessages.class); } @Override RestResult<ValidationMessages> markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsNotRequired(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsInComplete(long sectionId, long applicationId, long markedAsInCompleteById); @Override RestResult<Map<Long, Set<Long>>> getCompletedSectionsByOrganisation(long applicationId); @Override RestResult<List<Long>> getCompletedSectionIds(long applicationId, long organisationId); @Override RestResult<Boolean> allSectionsMarkedAsComplete(long applicationId); }### Answer: @Test public void markAsComplete() { long sectionId = 123L; long applicationId = 234L; long markedAsCompleteById = 345L; String expectedUrl = sectionRestUrl + "/mark-as-complete/" + sectionId + "/" + applicationId + "/" + markedAsCompleteById; ValidationMessages messages = new ValidationMessages(); setupPostWithRestResultExpectations(expectedUrl, ValidationMessages.class, null, messages, HttpStatus.OK); RestResult<ValidationMessages> result = service.markAsComplete(sectionId, applicationId, markedAsCompleteById); assertEquals(messages, result.getSuccess()); }
### Question: SectionStatusRestServiceImpl extends BaseRestService implements SectionStatusRestService { @Override public RestResult<Void> markAsNotRequired(long sectionId, long applicationId, long markedAsCompleteById) { return postWithRestResult(sectionRestURL + "/mark-as-not-required/" + sectionId + "/" + applicationId + "/" + markedAsCompleteById, Void.class); } @Override RestResult<ValidationMessages> markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsNotRequired(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsInComplete(long sectionId, long applicationId, long markedAsInCompleteById); @Override RestResult<Map<Long, Set<Long>>> getCompletedSectionsByOrganisation(long applicationId); @Override RestResult<List<Long>> getCompletedSectionIds(long applicationId, long organisationId); @Override RestResult<Boolean> allSectionsMarkedAsComplete(long applicationId); }### Answer: @Test public void markAsNotRequired() { long sectionId = 123L; long applicationId = 234L; long markedAsCompleteById = 345L; String expectedUrl = sectionRestUrl + "/mark-as-not-required/" + sectionId + "/" + applicationId + "/" + markedAsCompleteById; setupPostWithRestResultExpectations(expectedUrl, HttpStatus.OK); RestResult<Void> result = service.markAsNotRequired(sectionId, applicationId, markedAsCompleteById); assertTrue(result.isSuccess()); }
### Question: SectionStatusRestServiceImpl extends BaseRestService implements SectionStatusRestService { @Override public RestResult<Void> markAsInComplete(long sectionId, long applicationId, long markedAsInCompleteById) { return postWithRestResult(sectionRestURL + "/mark-as-in-complete/" + sectionId + "/" + applicationId + "/" + markedAsInCompleteById, Void.class); } @Override RestResult<ValidationMessages> markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsNotRequired(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsInComplete(long sectionId, long applicationId, long markedAsInCompleteById); @Override RestResult<Map<Long, Set<Long>>> getCompletedSectionsByOrganisation(long applicationId); @Override RestResult<List<Long>> getCompletedSectionIds(long applicationId, long organisationId); @Override RestResult<Boolean> allSectionsMarkedAsComplete(long applicationId); }### Answer: @Test public void markAsInComplete() { long sectionId = 123L; long applicationId = 234L; long markedAsCompleteById = 345L; String expectedUrl = sectionRestUrl + "/mark-as-in-complete/" + sectionId + "/" + applicationId + "/" + markedAsCompleteById; setupPostWithRestResultExpectations(expectedUrl, HttpStatus.OK); RestResult<Void> result = service.markAsInComplete(sectionId, applicationId, markedAsCompleteById); assertTrue(result.isSuccess()); }
### Question: SectionStatusRestServiceImpl extends BaseRestService implements SectionStatusRestService { @Override public RestResult<Map<Long, Set<Long>>> getCompletedSectionsByOrganisation(long applicationId) { return getWithRestResult(sectionRestURL + "/get-completed-sections-by-organisation/" + applicationId, mapOfLongToLongsSetType()); } @Override RestResult<ValidationMessages> markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsNotRequired(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsInComplete(long sectionId, long applicationId, long markedAsInCompleteById); @Override RestResult<Map<Long, Set<Long>>> getCompletedSectionsByOrganisation(long applicationId); @Override RestResult<List<Long>> getCompletedSectionIds(long applicationId, long organisationId); @Override RestResult<Boolean> allSectionsMarkedAsComplete(long applicationId); }### Answer: @Test public void getCompletedSectionsByOrganisation() { long applicationId = 123L; String expectedUrl = sectionRestUrl + "/get-completed-sections-by-organisation/" + applicationId; Map<Long, Set<Long>> expectedResult = new HashMap<>(); setupGetWithRestResultExpectations(expectedUrl, mapOfLongToLongsSetType(), expectedResult); RestResult<Map<Long, Set<Long>>> result = service.getCompletedSectionsByOrganisation(applicationId); assertEquals(expectedResult, result.getSuccess()); }
### Question: SectionStatusRestServiceImpl extends BaseRestService implements SectionStatusRestService { @Override public RestResult<List<Long>> getCompletedSectionIds(long applicationId, long organisationId) { return getWithRestResult(sectionRestURL + "/get-completed-sections/" + applicationId + "/" + organisationId, longsListType()); } @Override RestResult<ValidationMessages> markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsNotRequired(long sectionId, long applicationId, long markedAsCompleteById); @Override RestResult<Void> markAsInComplete(long sectionId, long applicationId, long markedAsInCompleteById); @Override RestResult<Map<Long, Set<Long>>> getCompletedSectionsByOrganisation(long applicationId); @Override RestResult<List<Long>> getCompletedSectionIds(long applicationId, long organisationId); @Override RestResult<Boolean> allSectionsMarkedAsComplete(long applicationId); }### Answer: @Test public void getCompletedSectionIds() { String expectedUrl = sectionRestUrl + "/get-completed-sections/123/456"; List<Long> returnedResponse = asList(1L, 2L, 3L); setupGetWithRestResultExpectations(expectedUrl, longsListType(), returnedResponse); List<Long> response = service.getCompletedSectionIds(123L, 456L).getSuccess(); assertEquals(returnedResponse, response); }
### Question: ApplicationNotificationTemplateRestServiceImpl extends BaseRestService implements ApplicationNotificationTemplateRestService { @Override public RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId) { return getWithRestResult(String.format("%s/%s/%s", baseUrl, "successful", competitionId), ApplicationNotificationTemplateResource.class); } @Override RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId); @Override RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId); @Override RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId); }### Answer: @Test public void getSuccessfulNotificationTemplate() { Long competitionId = 123L; String expectedUrl = baseUrl + "/successful/" + competitionId; ApplicationNotificationTemplateResource applicationNotificationTemplateResource = new ApplicationNotificationTemplateResource(); setupGetWithRestResultExpectations(expectedUrl, ApplicationNotificationTemplateResource.class, applicationNotificationTemplateResource); RestResult<ApplicationNotificationTemplateResource> result = service.getSuccessfulNotificationTemplate(competitionId); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals(applicationNotificationTemplateResource, result.getSuccess()); }
### Question: ApplicationNotificationTemplateRestServiceImpl extends BaseRestService implements ApplicationNotificationTemplateRestService { @Override public RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId) { return getWithRestResult(String.format("%s/%s/%s", baseUrl, "unsuccessful", competitionId), ApplicationNotificationTemplateResource.class); } @Override RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId); @Override RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId); @Override RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId); }### Answer: @Test public void getUnsuccessfulNotificationTemplate() { Long competitionId = 123L; String expectedUrl = baseUrl + "/unsuccessful/" + competitionId; ApplicationNotificationTemplateResource applicationNotificationTemplateResource = new ApplicationNotificationTemplateResource(); setupGetWithRestResultExpectations(expectedUrl, ApplicationNotificationTemplateResource.class, applicationNotificationTemplateResource); RestResult<ApplicationNotificationTemplateResource> result = service.getUnsuccessfulNotificationTemplate(competitionId); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals(applicationNotificationTemplateResource, result.getSuccess()); }
### Question: ApplicationNotificationTemplateRestServiceImpl extends BaseRestService implements ApplicationNotificationTemplateRestService { @Override public RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId) { return getWithRestResult(String.format("%s/%s/%s", baseUrl, "ineligible", competitionId), ApplicationNotificationTemplateResource.class); } @Override RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId); @Override RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId); @Override RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId); }### Answer: @Test public void getIneligibleNotificationTemplate() { long competitionId = 1L; String expectedUrl = baseUrl + "/ineligible/" + competitionId; ApplicationNotificationTemplateResource applicationNotificationTemplateResource = new ApplicationNotificationTemplateResource(); setupGetWithRestResultExpectations(expectedUrl, ApplicationNotificationTemplateResource.class, applicationNotificationTemplateResource); RestResult<ApplicationNotificationTemplateResource> result = service.getIneligibleNotificationTemplate(competitionId); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals(applicationNotificationTemplateResource, result.getSuccess()); }
### Question: SectionRestServiceImpl extends BaseRestService implements SectionRestService { @Override public RestResult<SectionResource> getById(Long sectionId) { return getWithRestResult(sectionRestURL + "/" + sectionId, SectionResource.class); } @Override RestResult<SectionResource> getById(Long sectionId); @Override RestResult<List<SectionResource>> getChildSectionsByParentId(long parentId); @Override RestResult<List<SectionResource>> getByCompetition(final Long competitionId); @Override RestResult<SectionResource> getSectionByQuestionId(Long questionId); @Override RestResult<Set<Long>> getQuestionsForSectionAndSubsections(Long sectionId); @Override RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(Long competitionId, SectionType type); @Override RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(Long competitionId); }### Answer: @Test public void getById() { long sectionId = 123L; String expectedUrl = sectionRestUrl + "/" + sectionId; SectionResource sectionResource = newSectionResource().build(); setupGetWithRestResultExpectations(expectedUrl, SectionResource.class, sectionResource); RestResult<SectionResource> result = service.getById(sectionId); assertEquals(sectionResource, result.getSuccess()); }
### Question: SectionRestServiceImpl extends BaseRestService implements SectionRestService { @Override public RestResult<List<SectionResource>> getByCompetition(final Long competitionId) { return getWithRestResult(sectionRestURL + "/get-by-competition/" + competitionId, sectionResourceListType()); } @Override RestResult<SectionResource> getById(Long sectionId); @Override RestResult<List<SectionResource>> getChildSectionsByParentId(long parentId); @Override RestResult<List<SectionResource>> getByCompetition(final Long competitionId); @Override RestResult<SectionResource> getSectionByQuestionId(Long questionId); @Override RestResult<Set<Long>> getQuestionsForSectionAndSubsections(Long sectionId); @Override RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(Long competitionId, SectionType type); @Override RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(Long competitionId); }### Answer: @Test public void getByCompetition() { long competitionId = 123L; String expectedUrl = sectionRestUrl + "/get-by-competition/" + competitionId; List<SectionResource> sectionResources = newSectionResource().build(2); setupGetWithRestResultExpectations(expectedUrl, sectionResourceListType(), sectionResources); RestResult<List<SectionResource>> result = service.getByCompetition(competitionId); assertEquals(sectionResources, result.getSuccess()); }
### Question: SectionRestServiceImpl extends BaseRestService implements SectionRestService { @Override public RestResult<SectionResource> getSectionByQuestionId(Long questionId) { return getWithRestResult(sectionRestURL + "/get-section-by-question-id/" + questionId, SectionResource.class); } @Override RestResult<SectionResource> getById(Long sectionId); @Override RestResult<List<SectionResource>> getChildSectionsByParentId(long parentId); @Override RestResult<List<SectionResource>> getByCompetition(final Long competitionId); @Override RestResult<SectionResource> getSectionByQuestionId(Long questionId); @Override RestResult<Set<Long>> getQuestionsForSectionAndSubsections(Long sectionId); @Override RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(Long competitionId, SectionType type); @Override RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(Long competitionId); }### Answer: @Test public void getSectionByQuestionId() { long questionId = 1L; String expectedUrl = sectionRestUrl + "/get-section-by-question-id/" + questionId; SectionResource sectionResource = newSectionResource().build(); setupGetWithRestResultExpectations(expectedUrl, SectionResource.class, sectionResource); RestResult<SectionResource> result = service.getSectionByQuestionId(questionId); assertEquals(sectionResource, result.getSuccess()); }
### Question: SectionRestServiceImpl extends BaseRestService implements SectionRestService { @Override public RestResult<Set<Long>> getQuestionsForSectionAndSubsections(Long sectionId) { return getWithRestResult(sectionRestURL + "/get-questions-for-section-and-subsections/" + sectionId, longsSetType()); } @Override RestResult<SectionResource> getById(Long sectionId); @Override RestResult<List<SectionResource>> getChildSectionsByParentId(long parentId); @Override RestResult<List<SectionResource>> getByCompetition(final Long competitionId); @Override RestResult<SectionResource> getSectionByQuestionId(Long questionId); @Override RestResult<Set<Long>> getQuestionsForSectionAndSubsections(Long sectionId); @Override RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(Long competitionId, SectionType type); @Override RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(Long competitionId); }### Answer: @Test public void getQuestionForSectionAndSubsections() { long sectionId = 1L; String expectedUrl = sectionRestUrl + "/get-questions-for-section-and-subsections/" + sectionId; Set<Long> questions = new HashSet<>(); setupGetWithRestResultExpectations(expectedUrl, longsSetType(), questions); RestResult<Set<Long>> result = service.getQuestionsForSectionAndSubsections(sectionId); assertEquals(questions, result.getSuccess()); }